Ich habe mypy --strict bisher richtig verwendet, aber ich habe mich gefragt, ob es wirklich streng ist, also habe ich mich entschlossen zu prüfen, ob es wichtige Optionen gibt, die nicht aktiviert wurden.
** Das Folgende ist die neueste Version 0.770 zum Buchungsdatum **
Die folgenden 6 Warnoptionen werden von --strict nicht aktiviert.
--disallow-any-unimported--disallow-any-expr--disallow-any-decorated--disallow-any-explicit--warn-unreachable--warn-incomplete-stubZunächst werden die von mypy --help angezeigten Warnoptionen unten zusammengefasst, ob sie von --strict aktiviert werden.
Es enthält jedoch nicht die Optionen, die standardmäßig aktiviert sind (siehe unten) (mypy --help zeigt die Optionen zum Unterdrücken an).
--strict-optional--warn-no-return--disallow-untyped-globals--disallow-redefinitionAktiviert mit --strict: ✅ / Disabled: ❌
Config file
| option | description | |
|---|---|---|
| ✅ | --warn-unused-configs | 
Warn about unused '[mypy- | 
Disallow dynamic typing
| option | description | |
|---|---|---|
| ❌ | --disallow-any-unimported | 
Disallow Any types resulting from unfollowed imports | 
| ❌ | --disallow-any-expr | 
Disallow all expressions that have type Any | 
| ❌ | --disallow-any-decorated | 
Disallow functions that have Any in their signature after decorator transformation | 
| ❌ | --disallow-any-explicit | 
Disallow explicit Any in type positions | 
| ✅ | --disallow-any-generics | 
Disallow usage of generic types that do not specify explicit type parameters | 
| ✅ | --disallow-subclassing-any | 
Disallow subclassing values of type Any when defining classes | 
Untyped definitions and calls
| option | description | |
|---|---|---|
| ✅ | --disallow-untyped-calls | 
Disallow calling functions without type annotations from functions with type annotations | 
| ✅ | --disallow-untyped-defs | 
Disallow defining functions without type annotations or with incomplete type annotations | 
| ✅ | --disallow-incomplete-defs | 
Disallow defining functions with incomplete type annotations | 
| ✅ | --check-untyped-defs | 
Type check the interior of functions without type annotations | 
| ✅ | --disallow-untyped-decorators | 
Disallow decorating typed functions with untyped decorators | 
None and Optional handling
| option | description | |
|---|---|---|
| ✅ | --no-implicit-optional | 
Don't assume arguments with default values of None are Optional | 
Configuring warnings
| option | description | |
|---|---|---|
| ✅ | --warn-redundant-casts | 
Warn about casting an expression to its inferred type | 
| ✅ | --warn-unused-ignores | 
Warn about unneeded # type: ignore comments | 
| ✅ | --warn-return-any | 
Warn about returning values of type Any from non-Any typed functions | 
| ❌ | --warn-unreachable | 
Warn about statements or expressions inferred to be unreachable or redundant | 
Miscellaneous strictness flags
| option | description | |
|---|---|---|
| ✅ | --no-implicit-reexport | 
Treat imports as private unless aliased | 
| ✅ | --strict-equality | 
Prohibit equality, identity, and container checks for non-overlapping types | 
Advanced options
| option | description | |
|---|---|---|
| ❌ | --warn-incomplete-stub | 
Warn if missing type annotation in typeshed, only relevant with --disallow-untyped-defs or --disallow-incomplete-defs enabled | 
--disallow-any-unimported
Ohne den Stub wäre der Typ der externen Bibliothek ein Alias für "typing.Any", aber warnen Sie, dass Sie ihn verwenden.
sample.py
import numpy as np  # type: ignore
def func() -> np.ndarray:
    return np.array(1)
$ mypy --strict --show-error-code --pretty sample.py
Success: no issues found in 1 source file
$ mypy --disallow-any-unimported --show-error-code --pretty sample.py
sample.py:3: error: Return type becomes "Any" due to an unfollowed import  [no-any-unimported]
    def func() -> np.ndarray:
    ^
Found 1 error in 1 file (checked 1 source file)
Sie können es wie folgt ändern.
- def func() -> np.ndarray:
+ def func() -> t.Any:
Ich habe mich gefragt, ob es voll von "Any" sein würde, aber "np.ndarray" ist schließlich auch nur eine Illusion, also könnte es in Ordnung sein. Ich denke, dass es Zeiten gibt, in denen ich "np.ndarray" als Kommentar schreibe, also denke ich, dass es eine individuelle Entscheidung ist.
--disallow-any-expr
Warnung für Ausdrücke, die typing.Any enthalten.
Raus mit np.array (1) + np.array (2). Sie können fast nichts tun, ohne einen Stummel zu machen.
--disallow-any-decorated
Warnung, dass die Funktion nach dem Durchlaufen des Dekorators "typing.Any" im Argument oder im Rückgabewert hat.
sample.py
from abc import ABC, abstractmethod
from functools import wraps
import typing as t
class A(ABC):
    @abstractmethod
    def func_a(a: t.Any) -> None:
        pass
def deco(f: t.Callable[[int], int]) -> t.Callable[[int], t.Any]:
    @wraps(f)
    def wrapper(a: int) -> t.Any:
        return t.cast(t.Any, f(a))
    
    return wrapper
@deco
def func_b(a: int) -> int:
    return 0
$ mypy --strict --show-error-code --pretty sample.py
Success: no issues found in 1 source file
$ mypy --disallow-any-decorated --show-error-code --pretty sample.py
sample.py:8: error: Type of decorated function contains type "Any" ("Callable[[Any], None]")  [misc]
        def func_a(a: t.Any) -> None:
        ^
sample.py:21: error: Type of decorated function contains type "Any" ("Callable[[int], Any]")  [misc]
    def func_b(a: int) -> int:
    ^
Found 2 errors in 1 file (checked 1 source file)
Sofern eine normale Funktion nicht "--disallow-any-explizit" hinzufügt, können Sie "typing.Any" als Argument verwenden, aber ich verstehe nicht, was es bedeutet, nur den Dekorateur (und "--disallow-") zu spezialisieren. Ich habe nicht das Gefühl, dass irgendetwas explizit gemacht werden kann.
--disallow-any-explicit
Warnen Sie explizit "typing.Any". Streng.
--warn-unreachable
Warnung bei Nichtliefercode.
sample.py
def process(x: int) -> None:
    if isinstance(x, int) or x > 7:
        print(str(x) + "bad")
    else:
        print(str(x) + "bad")
(Der Code von https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-warn-unreachable wurde ein wenig geändert.)
$ mypy --strict --show-error-code --pretty sample.py
Success: no issues found in 1 source file
$ mypy --warn-unreachable --show-error-code --pretty sample.py
sample.py:2: error: Right operand of 'or' is never evaluated  [unreachable]
        if isinstance(x, int) or x > 7:
                                 ^
sample.py:5: error: Statement is unreachable  [unreachable]
            print(str(x) + "bad")
            ^
Found 2 errors in 1 file (checked 1 source file)
Nicht alle Nichtzustellungscodes können erkannt werden, aber ist es nicht schlecht?
--warn-incomplete-stub
Warnung vor Stichleitungen. Ich bin mir nicht sicher, weil stubgen überhaupt nicht funktioniert.
Im Dokument
This flag is mainly intended to be used by people who want contribute to typeshed and would like a convenient way to find gaps and omissions.
Ist es okay, weil es heißt?
Persönlich dachte ich zusätzlich zu "--strict", dass die folgenden zwei in Betracht gezogen werden könnten.
--disallow-any-unimported--warn-unreachableErstens wird mypy nur durch Trägheit verwendet. Wenn es also etwas gibt, das um Pyright, Pyre, pytype einfach zu verwenden ist, würde ich gerne wechseln.
Verschiedenes Vergleich
| Werkzeugname | Sprache | GitHub-Repository | Sternnummer(2020/5/2 22:41 Derzeit) | 
|---|---|---|---|
| mypy | Python | https://github.com/python/mypy | 8379 | 
| pytype | Python | https://github.com/google/pytype | 2629 | 
| Pyre | OCaml | https://github.com/facebook/pyre-check | 3334 | 
| Pyright | TypeScript | https://github.com/microsoft/pyright | 5107 | 
--Offizielles Dokument
Recommended Posts