Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark, in light modeAuto light/dark, in dark modeSkip to content
mypy 1.19.1 documentation
Logo
mypy 1.19.1 documentation

First steps

Type system reference

Configuring and running mypy

Miscellaneous

Project Links

Back to top

Error codes enabled by default

This section documents various errors codes that mypy can generatewith default options. SeeError codes for general documentationabout error codes.Error codes for optional checks documents additionalerror codes that you can enable.

Check that attribute exists [attr-defined]

Mypy checks that an attribute is defined in the target class or modulewhen using the dot operator. This applies to both getting and settingan attribute. New attributes are defined by assignments in the classbody, or assignments toself.x in methods. These assignments don’tgenerateattr-defined errors.

Example:

classResource:def__init__(self,name:str)->None:self.name=namer=Resource('x')print(r.name)# OKprint(r.id)# Error: "Resource" has no attribute "id"  [attr-defined]r.id=5# Error: "Resource" has no attribute "id"  [attr-defined]

This error code is also generated if an imported name is not definedin the module in afrom...import statement (as long as thetarget module can be found):

# Error: Module "os" has no attribute "non_existent"  [attr-defined]fromosimportnon_existent

A reference to a missing attribute is given theAny type. In theabove example, the type ofnon_existent will beAny, which canbe important if you silence the error.

Check that attribute exists in each union item [union-attr]

If you access the attribute of a value with a union type, mypy checksthat the attribute is defined forevery type in thatunion. Otherwise the operation can fail at runtime. This also appliesto optional types.

Example:

classCat:defsleep(self)->None:...defmiaow(self)->None:...classDog:defsleep(self)->None:...deffollow_me(self)->None:...deffunc(animal:Cat|Dog)->None:# OK: 'sleep' is defined for both Cat and Doganimal.sleep()# Error: Item "Cat" of "Cat | Dog" has no attribute "follow_me"  [union-attr]animal.follow_me()

You can often work around these errors by usingassertisinstance(obj,ClassName)orassertobjisnotNone to tell mypy that you know that the type is more specificthan what mypy thinks.

Check that name is defined [name-defined]

Mypy expects that all references to names have a correspondingdefinition in an active scope, such as an assignment, functiondefinition or an import. This can catch missing definitions, missingimports, and typos.

This example accidentally callssort() instead ofsorted():

x=sort([3,2,4])# Error: Name "sort" is not defined  [name-defined]

Check that a variable is not used before it’s defined [used-before-def]

Mypy will generate an error if a name is used before it’s defined.While the name-defined check will catch issues with names that are undefined,it will not flag if a variable is used and then defined later in the scope.used-before-def check will catch such cases.

Example:

print(x)# Error: Name "x" is used before definition [used-before-def]x=123

Check arguments in calls [call-arg]

Mypy expects that the number and names of arguments match the called function.Note that argument type checks have a separate error codearg-type.

Example:

defgreet(name:str)->None:print('hello',name)greet('jack')# OKgreet('jill','jack')# Error: Too many arguments for "greet"  [call-arg]

Check argument types [arg-type]

Mypy checks that argument types in a call match the declared argumenttypes in the signature of the called function (if one exists).

Example:

deffirst(x:list[int])->int:returnx[0]ifxelse0t=(5,4)# Error: Argument 1 to "first" has incompatible type "tuple[int, int]";#        expected "list[int]"  [arg-type]print(first(t))

Check calls to overloaded functions [call-overload]

When you call an overloaded function, mypy checks that at least one ofthe signatures of the overload items match the argument types in thecall.

Example:

fromtypingimportoverload@overloaddefinc_maybe(x:None)->None:...@overloaddefinc_maybe(x:int)->int:...definc_maybe(x:int|None)->int|None:ifxisNone:returnNoneelse:returnx+1inc_maybe(None)# OKinc_maybe(5)# OK# Error: No overload variant of "inc_maybe" matches argument type "float"  [call-overload]inc_maybe(1.2)

Check validity of types [valid-type]

Mypy checks that each type annotation and any expression thatrepresents a type is a valid type. Examples of valid types includeclasses, union types, callable types, type aliases, and literal types.Examples of invalid types include bare integer literals, functions,variables, and modules.

This example incorrectly uses the functionlog as a type:

deflog(x:object)->None:print('log:',repr(x))# Error: Function "t.log" is not valid as a type  [valid-type]deflog_all(objs:list[object],f:log)->None:forxinobjs:f(x)

You can useCallable as the type for callable objects:

fromcollections.abcimportCallable# OKdeflog_all(objs:list[object],f:Callable[[object],None])->None:forxinobjs:f(x)

Check the validity of a class’s metaclass [metaclass]

Mypy checks whether the metaclass of a class is valid. The metaclassmust be a subclass oftype. Further, the class hierarchy must yielda consistent metaclass. For more details, see thePython documentation

Note that mypy’s metaclass checking is limited and may produce false-positives.See alsoGotchas and limitations of metaclass support.

Example with an error:

classGoodMeta(type):passclassBadMeta:passclassA1(metaclass=GoodMeta):# OKpassclassA2(metaclass=BadMeta):# Error:  Metaclasses not inheriting from "type" are not supported  [metaclass]pass

Require annotation if variable type is unclear [var-annotated]

In some cases mypy can’t infer the type of a variable without anexplicit annotation. Mypy treats this as an error. This typicallyhappens when you initialize a variable with an empty collection orNone. If mypy can’t infer the collection item type, mypy replacesany parts of the type it couldn’t infer withAny and generates anerror.

Example with an error:

classBundle:def__init__(self)->None:# Error: Need type annotation for "items"#        (hint: "items: list[<type>] = ...")  [var-annotated]self.items=[]reveal_type(Bundle().items)# list[Any]

To address this, we add an explicit annotation:

classBundle:def__init__(self)->None:self.items:list[str]=[]# OKreveal_type(Bundle().items)# list[str]

Check validity of overrides [override]

Mypy checks that an overridden method or attribute is compatible withthe base class. A method in a subclass must accept all argumentsthat the base class method accepts, and the return type must conformto the return type in the base class (Liskov substitution principle).

Argument types can be more general is a subclass (i.e., they can varycontravariantly). The return type can be narrowed in a subclass(i.e., it can vary covariantly). It’s okay to define additionalarguments in a subclass method, as long all extra arguments have defaultvalues or can be left out (*args, for example).

Example:

classBase:defmethod(self,arg:int)->int|None:...classDerived(Base):defmethod(self,arg:int|str)->int:# OK...classDerivedBad(Base):# Error: Argument 1 of "method" is incompatible with "Base"  [override]defmethod(self,arg:bool)->int:...

Check that function returns a value [return]

If a function has a non-None return type, mypy expects that thefunction always explicitly returns a value (or raises an exception).The function should not fall off the end of the function, since thisis often a bug.

Example:

# Error: Missing return statement  [return]defshow(x:int)->int:print(x)# Error: Missing return statement  [return]defpred1(x:int)->int:ifx>0:returnx-1# OKdefpred2(x:int)->int:ifx>0:returnx-1else:raiseValueError('not defined for zero')

Check that functions don’t have empty bodies outside stubs [empty-body]

This error code is similar to the[return] code but is emitted specificallyfor functions and methods with empty bodies (if they are annotated withnon-trivial return type). Such a distinction exists because in some contextsan empty body can be valid, for example for an abstract method or in a stubfile. Also old versions of mypy used to unconditionally allow functions withempty bodies, so having a dedicated error code simplifies cross-versioncompatibility.

Note that empty bodies are allowed for methods inprotocols, and such methodsare considered implicitly abstract:

fromabcimportabstractmethodfromtypingimportProtocolclassRegularABC:@abstractmethoddeffoo(self)->int:pass# OKdefbar(self)->int:pass# Error: Missing return statement  [empty-body]classProto(Protocol):defbar(self)->int:pass# OK

Check that return value is compatible [return-value]

Mypy checks that the returned value is compatible with the typesignature of the function.

Example:

deffunc(x:int)->str:# Error: Incompatible return value type (got "int", expected "str")  [return-value]returnx+1

Check types in assignment statement [assignment]

Mypy checks that the assigned expression is compatible with theassignment target (or targets).

Example:

classResource:def__init__(self,name:str)->None:self.name=namer=Resource('A')r.name='B'# OK# Error: Incompatible types in assignment (expression has type "int",#        variable has type "str")  [assignment]r.name=5

Check that assignment target is not a method [method-assign]

In general, assigning to a method on class object or instance (a.k.a.monkey-patching) is ambiguous in terms of types, since Python’s static typesystem cannot express the difference between bound and unbound callable types.Consider this example:

classA:deff(self)->None:passdefg(self)->None:passdefh(self:A)->None:passA.f=h# Type of h is Callable[[A], None]A().f()# This worksA.f=A().g# Type of A().g is Callable[[], None]A().f()# ...but this also works at runtime

To prevent the ambiguity, mypy will flag both assignments by default. If thiserror code is disabled, mypy will treat the assigned value in all method assignments as unbound,so only the second assignment will still generate an error.

Note

This error code is a subcode of the more general[assignment] code.

Check type variable values [type-var]

Mypy checks that value of a type variable is compatible with a valuerestriction or the upper bound type.

Example (Python 3.12 syntax):

defadd[T1:(int,float)](x:T1,y:T1)->T1:returnx+yadd(4,5.5)# OK# Error: Value of type variable "T1" of "add" cannot be "str"  [type-var]add('x','y')

Check uses of various operators [operator]

Mypy checks that operands support a binary or unary operation, such as+ or~. Indexing operations are so common that they have theirown error codeindex (see below).

Example:

# Error: Unsupported operand types for + ("int" and "str")  [operator]1+'x'

Check indexing operations [index]

Mypy checks that the indexed value in indexing operation such asx[y] supports indexing, and that the index expression has a validtype.

Example:

a={'x':1,'y':2}a['x']# OK# Error: Invalid index type "int" for "dict[str, int]"; expected type "str"  [index]print(a[1])# Error: Invalid index type "bytes" for "dict[str, int]"; expected type "str"  [index]a[b'x']=4

Check list items [list-item]

When constructing a list using[item,...], mypy checks that each itemis compatible with the list type that is inferred from the surroundingcontext.

Example:

# Error: List item 0 has incompatible type "int"; expected "str"  [list-item]a:list[str]=[0]

Check dict items [dict-item]

When constructing a dictionary using{key:value,...} ordict(key=value,...),mypy checks that each key and value is compatible with the dictionary type that isinferred from the surrounding context.

Example:

# Error: Dict entry 0 has incompatible type "str": "str"; expected "str": "int"  [dict-item]d:dict[str,int]={'key':'value'}

Check TypedDict items [typeddict-item]

When constructing a TypedDict object, mypy checks that each key and value is compatiblewith the TypedDict type that is inferred from the surrounding context.

When getting a TypedDict item, mypy checks that the keyexists. When assigning to a TypedDict, mypy checks that both thekey and the value are valid.

Example:

fromtypingimportTypedDictclassPoint(TypedDict):x:inty:int# Error: Incompatible types (expression has type "float",#        TypedDict item "x" has type "int")  [typeddict-item]p:Point={'x':1.2,'y':4}

Check TypedDict Keys [typeddict-unknown-key]

When constructing a TypedDict object, mypy checks whether thedefinition contains unknown keys, to catch invalid keys andmisspellings. On the other hand, mypy will not generate an error whena previously constructed TypedDict value with extra keys is passedto a function as an argument, since TypedDict values supportstructural subtyping (“static duck typing”) and the keys are assumedto have been validated at the point of construction. Example:

fromtypingimportTypedDictclassPoint(TypedDict):x:inty:intclassPoint3D(Point):z:intdefadd_x_coordinates(a:Point,b:Point)->int:returna["x"]+b["x"]a:Point={"x":1,"y":4}b:Point3D={"x":2,"y":5,"z":6}add_x_coordinates(a,b)# OK# Error: Extra key "z" for TypedDict "Point"  [typeddict-unknown-key]add_x_coordinates(a,{"x":1,"y":4,"z":5})

Setting a TypedDict item using an unknown key will also generate thiserror, since it could be a misspelling:

a:Point={"x":1,"y":2}# Error: Extra key "z" for TypedDict "Point"  [typeddict-unknown-key]a["z"]=3

Reading an unknown key will generate the more general (and serious)typeddict-item error, which is likely to result in an exception atruntime:

a:Point={"x":1,"y":2}# Error: TypedDict "Point" has no key "z"  [typeddict-item]_=a["z"]

Note

This error code is a subcode of the wider[typeddict-item] code.

Check that type of target is known [has-type]

Mypy sometimes generates an error when it hasn’t inferred any type fora variable being referenced. This can happen for references tovariables that are initialized later in the source file, and forreferences across modules that form an import cycle. When thishappens, the reference gets an implicitAny type.

In this example the definitions ofx andy are circular:

classProblem:defset_x(self)->None:# Error: Cannot determine type of "y"  [has-type]self.x=self.ydefset_y(self)->None:self.y=self.x

To work around this error, you can add an explicit type annotation tothe target variable or attribute. Sometimes you can also reorganizethe code so that the definition of the variable is placed earlier thanthe reference to the variable in a source file. Untangling cyclicimports may also help.

We add an explicit annotation to they attribute to work aroundthe issue:

classProblem:defset_x(self)->None:self.x=self.y# OKdefset_y(self)->None:self.y:int=self.x# Added annotation here

Check for an issue with imports [import]

Mypy generates an error if it can’t resolve animport statement.This is a parent error code ofimport-not-found andimport-untyped

SeeMissing imports for how to work around these errors.

Check that import target can be found [import-not-found]

Mypy generates an error if it can’t find the source code or a stub filefor an imported module.

Example:

# Error: Cannot find implementation or library stub for module named "m0dule_with_typo"  [import-not-found]importm0dule_with_typo

SeeMissing imports for how to work around these errors.

Check that import target can be found [import-untyped]

Mypy generates an error if it can find the source code for an imported module,but that module does not provide type annotations (viaPEP 561).

Example:

# Error: Library stubs not installed for "bs4"  [import-untyped]importbs4# Error: Skipping analyzing "no_py_typed": module is installed, but missing library stubs or py.typed marker  [import-untyped]importno_py_typed

In some cases, these errors can be fixed by installing an appropriatestub package. SeeMissing imports for more details.

Check that each name is defined once [no-redef]

Mypy may generate an error if you have multiple definitions for a namein the same namespace. The reason is that this is often an error, asthe second definition may overwrite the first one. Also, mypy oftencan’t be able to determine whether references point to the first orthe second definition, which would compromise type checking.

If you silence this error, all references to the defined name refer tothefirst definition.

Example:

classA:def__init__(self,x:int)->None:...classA:# Error: Name "A" already defined on line 1  [no-redef]def__init__(self,x:str)->None:...# Error: Argument 1 to "A" has incompatible type "str"; expected "int"#        (the first definition wins!)A('x')

Check that called function returns a value [func-returns-value]

Mypy reports an error if you call a function with aNonereturn type and don’t ignore the return value, as this isusually (but not always) a programming error.

In this example, theiff() check is always false sincefreturnsNone:

deff()->None:...# OK: we don't do anything with the return valuef()# Error: "f" does not return a value (it only ever returns None)  [func-returns-value]iff():print("not false")

Check instantiation of abstract classes [abstract]

Mypy generates an error if you try to instantiate an abstract baseclass (ABC). An abstract base class is a class with at least oneabstract method or attribute. (See alsoabc module documentation)

Sometimes a class is made accidentally abstract, often due to anunimplemented abstract method. In a case like this you need to providean implementation for the method to make the class concrete(non-abstract).

Example:

fromabcimportABCMeta,abstractmethodclassPersistent(metaclass=ABCMeta):@abstractmethoddefsave(self)->None:...classThing(Persistent):def__init__(self)->None:......# No "save" method# Error: Cannot instantiate abstract class "Thing" with abstract attribute "save"  [abstract]t=Thing()

Safe handling of abstract type object types [type-abstract]

Mypy always allows instantiating (calling) type objects typed astype[t],even if it is not known thatt is non-abstract, since it is a commonpattern to create functions that act as object factories (custom constructors).Therefore, to prevent issues described in the above section, when an abstracttype object is passed wheretype[t] is expected, mypy will give an error.Example (Python 3.12 syntax):

fromabcimportABCMeta,abstractmethodclassConfig(metaclass=ABCMeta):@abstractmethoddefget_value(self,attr:str)->str:...defmake_many[T](typ:type[T],n:int)->list[T]:return[typ()for_inrange(n)]# This will raise if typ is abstract# Error: Only concrete class can be given where "type[Config]" is expected [type-abstract]make_many(Config,5)

Check that call to an abstract method via super is valid [safe-super]

Abstract methods often don’t have any default implementation, i.e. theirbodies are just empty. Calling such methods in subclasses viasuper()will cause runtime errors, so mypy prevents you from doing so:

fromabcimportabstractmethodclassBase:@abstractmethoddeffoo(self)->int:...classSub(Base):deffoo(self)->int:returnsuper().foo()+1# error: Call to abstract method "foo" of "Base" with# trivial body via super() is unsafe  [safe-super]Sub().foo()# This will crash at runtime.

Mypy considers the following as trivial bodies: apass statement, a literalellipsis..., a docstring, and araiseNotImplementedError statement.

Check the target of NewType [valid-newtype]

The target of aNewType definition must be a class type. It can’tbe a union type,Any, or various other special types.

You can also get this error if the target has been imported from amodule whose source mypy cannot find, since any such definitions aretreated by mypy as values withAny types. Example:

fromtypingimportNewType# The source for "acme" is not available for mypyfromacmeimportEntity# type: ignore# Error: Argument 2 to NewType(...) must be subclassable (got "Any")  [valid-newtype]UserEntity=NewType('UserEntity',Entity)

To work around the issue, you can either give mypy access to the sourcesforacme or create a stub file for the module. SeeMissing importsfor more information.

Check the return type of __exit__ [exit-return]

If mypy can determine that__exit__ always returnsFalse, mypychecks that the return type isnotbool. The boolean value ofthe return type affects which lines mypy thinks are reachable after awith statement, since any__exit__ method that can returnTrue may swallow exceptions. An imprecise return type can resultin mysterious errors reported nearwith statements.

To fix this, use eithertyping.Literal[False] orNone as the return type. ReturningNone is equivalent toreturningFalse in this context, since both are treated as falsevalues.

Example:

classMyContext:...def__exit__(self,exc,value,tb)->bool:# Errorprint('exit')returnFalse

This produces the following output from mypy:

example.py:3: error: "bool" is invalid as return type for "__exit__" that always returns Falseexample.py:3: note: Use "typing_extensions.Literal[False]" as the return type or change it to    "None"example.py:3: note: If return type of "__exit__" implies that it may return True, the context    manager may swallow exceptions

You can useLiteral[False] to fix the error:

fromtypingimportLiteralclassMyContext:...def__exit__(self,exc,value,tb)->Literal[False]:# OKprint('exit')returnFalse

You can also useNone:

classMyContext:...def__exit__(self,exc,value,tb)->None:# Also OKprint('exit')

Check that naming is consistent [name-match]

The definition of a named tuple or a TypedDict must be namedconsistently when using the call-based syntax. Example:

fromtypingimportNamedTuple# Error: First argument to namedtuple() should be "Point2D", not "Point"Point2D=NamedTuple("Point",[("x",int),("y",int)])

Check that literal is used where expected [literal-required]

There are some places where only a (string) literal value is expected forthe purposes of static type checking, for example aTypedDict key, ora__match_args__ item. Providing astr-valued variable in such contextswill result in an error. Note that in many cases you can also useFinalorLiteral variables. Example:

fromtypingimportFinal,Literal,TypedDictclassPoint(TypedDict):x:inty:intdeftest(p:Point)->None:X:Final="x"p[X]# OKY:Literal["y"]="y"p[Y]# OKkey="x"# Inferred type of key is `str`# Error: TypedDict key must be a string literal;#   expected one of ("x", "y")  [literal-required]p[key]

Check that overloaded functions have an implementation [no-overload-impl]

Overloaded functions outside of stub files must be followed by a non overloadedimplementation.

fromtypingimportoverload@overloaddeffunc(value:int)->int:...@overloaddeffunc(value:str)->str:...# presence of required function below is checkeddeffunc(value):pass# actual implementation

Check that coroutine return value is used [unused-coroutine]

Mypy ensures that return values of async def functions are notignored, as this is usually a programming error, as the coroutinewon’t be executed at the call site.

asyncdeff()->None:...asyncdefg()->None:f()# Error: missing awaitawaitf()# OK

You can work around this error by assigning the result to a temporary,otherwise unused variable:

_=f()# No error

Warn about top level await expressions [top-level-await]

This error code is separate from the general[syntax] errors, because insome environments (e.g. IPython) a top levelawait is allowed. In suchenvironments a user may want to use--disable-error-code=top-level-await,which allows one to still have errors for other improper uses ofawait,for example:

asyncdeff()->None:...top=awaitf()# Error: "await" outside function  [top-level-await]

Warn about await expressions used outside of coroutines [await-not-async]

await must be used inside a coroutine.

asyncdeff()->None:...defg()->None:awaitf()# Error: "await" outside coroutine ("async def")  [await-not-async]

Check types in assert_type [assert-type]

The inferred type for an expression passed toassert_type must matchthe provided type.

fromtyping_extensionsimportassert_typeassert_type([1],list[int])# OKassert_type([1],list[str])# Error

Check that function isn’t used in boolean context [truthy-function]

Functions will always evaluate to true in boolean contexts.

deff():...iff:# Error: Function "Callable[[], Any]" could always be true in boolean context  [truthy-function]pass

Check that string formatting/interpolation is type-safe [str-format]

Mypy will check that f-strings,str.format() calls, and% interpolationsare valid (when corresponding template is a literal string). This includeschecking number and types of replacements, for example:

# Error: Cannot find replacement for positional format specifier 1 [str-format]"{} and{}".format("spam")"{} and{}".format("spam","eggs")# OK# Error: Not all arguments converted during string formatting [str-format]"{} and{}".format("spam","eggs","cheese")# Error: Incompatible types in string interpolation# (expression has type "float", placeholder has type "int") [str-format]"{:d}".format(3.14)

Check for implicit bytes coercions [str-bytes-safe]

Warn about cases where a bytes object may be converted to a string in an unexpected manner.

b=b"abc"# Error: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc".# If this is desired behavior, use f"{x!r}" or "{!r}".format(x).# Otherwise, decode the bytes [str-bytes-safe]print(f"The alphabet starts with{b}")# Okayprint(f"The alphabet starts with{b!r}")# The alphabet starts with b'abc'print(f"The alphabet starts with{b.decode('utf-8')}")# The alphabet starts with abc

Check that overloaded functions don’t overlap [overload-overlap]

Warn if multiple@overload variants overlap in potentially unsafe ways.This guards against the following situation:

fromtypingimportoverloadclassA:...classB(A):...@overloaddeffoo(x:B)->int:...# Error: Overloaded function signatures 1 and 2 overlap with incompatible return types  [overload-overlap]@overloaddeffoo(x:A)->str:...deffoo(x):...deftakes_a(a:A)->str:returnfoo(a)a:A=B()value=takes_a(a)# mypy will think that value is a str, but it could actually be an intreveal_type(value)# Revealed type is "builtins.str"

Note that in cases where you ignore this error, mypy will usually still infer thetypes you expect.

Seeoverloading for more explanation.

Check for overload signatures that cannot match [overload-cannot-match]

Warn if an@overload variant can never be matched, because an earlieroverload has a wider signature. For example, this can happen if the twooverloads accept the same parameters and each parameter on the first overloadhas the same type or a wider type than the corresponding parameter on the secondoverload.

Example:

fromtypingimportoverload,Union@overloaddefprocess(response1:object,response2:object)->object:...@overloaddefprocess(response1:int,response2:int)->int:# E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader  [overload-cannot-match]...defprocess(response1:object,response2:object)->object:returnresponse1+response2

Notify about an annotation in an unchecked function [annotation-unchecked]

Sometimes a user may accidentally omit an annotation for a function, and mypywill not check the body of this function (unless one uses--check-untyped-defs or--disallow-untyped-defs). To avoidsuch situations go unnoticed, mypy will show a note, if there are any typeannotations in an unchecked function:

deftest_assignment():# "-> None" return annotation is missing# Note: By default the bodies of untyped functions are not checked,# consider using --check-untyped-defs [annotation-unchecked]x:int="no way"

Note that mypy will still exit with return code0, since such behaviour isspecified byPEP 484.

Decorator preceding property not supported [prop-decorator]

Mypy does not yet support analysis of decorators that precede the propertydecorator. If the decorator does not preserve the declared type of the property,mypy will not infer the correct type for the declaration. If the decorator cannotbe moved after the@property decorator, then you must use a type ignorecomment:

classMyClass:@special# type: ignore[prop-decorator]@propertydefmagic(self)->str:return"xyzzy"

Note

For backward compatibility, this error code is a subcode of the generic[misc] code.

Report syntax errors [syntax]

If the code being checked is not syntactically valid, mypy issues asyntax error. Most, but not all, syntax errors areblocking errors:they can’t be ignored with a#type:ignore comment.

ReadOnly key of a TypedDict is mutated [typeddict-readonly-mutated]

Consider this example:

fromdatetimeimportdatetimefromtypingimportTypedDictfromtyping_extensionsimportReadOnlyclassUser(TypedDict):username:ReadOnly[str]last_active:datetimeuser:User={'username':'foobar','last_active':datetime.now()}user['last_active']=datetime.now()# okuser['username']='other'# error: ReadOnly TypedDict key "key" TypedDict is mutated  [typeddict-readonly-mutated]

PEP 705 specifieshowReadOnly special form works forTypedDict objects.

Check thatTypeIs narrows types [narrowed-type-not-subtype]

PEP 742 requires that whenTypeIs is used, the narrowedtype must be a subtype of the original type:

fromtyping_extensionsimportTypeIsdeff(x:int)->TypeIs[str]:# Error, str is not a subtype of int...defg(x:object)->TypeIs[str]:# OK...

String appears in a context which expects a TypeForm [maybe-unrecognized-str-typeform]

TypeForm literals may contain string annotations:

typx1:TypeForm=str|Nonetypx2:TypeForm='str | None'# OKtypx3:TypeForm='str'|None# OK

However TypeForm literals containing a string annotation can only be recognizedby mypy in the following locations:

typx_var:TypeForm='str | None'# assignment r-valuedeffunc(typx_param:TypeForm)->TypeForm:return'str | None'# returned expressionfunc('str | None')# callable's argument

If you try to use a string annotation in some other locationwhich expects a TypeForm, the string value will always be treated as astreven if aTypeForm would be more appropriate and this error codewill be generated:

# Error: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize.  [maybe-unrecognized-str-typeform]# Error: List item 0 has incompatible type "str"; expected "TypeForm[Any]"  [list-item]list_of_typx:list[TypeForm]=['str | None',float]

Fix the error by surrounding the entire type withTypeForm(...):

list_of_typx:list[TypeForm]=[TypeForm('str | None'),float]# OK

Similarly, if you try to use a string literal in a location which expects aTypeForm, this error code will be generated:

dict_of_typx={'str_or_none':TypeForm(str|None)}# Error: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize.  [maybe-unrecognized-str-typeform]list_of_typx:list[TypeForm]=[dict_of_typx['str_or_none']]

Fix the error by adding#type:ignore[maybe-unrecognized-str-typeform]to the line with the string literal:

dict_of_typx={'str_or_none':TypeForm(str|None)}list_of_typx:list[TypeForm]=[dict_of_typx['str_or_none']]# type: ignore[maybe-unrecognized-str-typeform]

Miscellaneous checks [misc]

Mypy performs numerous other, less commonly failing checks that don’thave specific error codes. These use themisc error code. Otherthan being used for multiple unrelated errors, themisc error codeis not special. For example, you can ignore all errors in thiscategory by using#type:ignore[misc] comment. Since these errorsare not expected to be common, it’s unlikely that you’ll see twodifferent errors with themisc code on a single line – thoughthis can certainly happen once in a while.

Note

Future mypy versions will likely add new error codes for some errorsthat currently use themisc error code.

On this page

[8]ページ先頭

©2009-2025 Movatter.jp