Disallow dynamic typing

The Any type is used represent a value that has a dynamic type.The —disallow-any family of flags will disallow various uses of the Any type ina module – this lets us strategically disallow the use of dynamic typing in a controlled way.

The following options are available:

  • —disallow-any-unimported
  • This flag disallows usage of types that come from unfollowed imports(such types become aliases for Any). Unfollowed imports occur eitherwhen the imported module does not exist or when —follow-imports=skipis set.
  • —disallow-any-expr
  • This flag disallows all expressions in the module that have type Any.If an expression of type Any appears anywhere in the modulemypy will output an error unless the expression is immediatelyused as an argument to cast() or assigned to a variable with anexplicit type annotation.

In addition, declaring a variable of type Anyor casting to type Any is not allowed. Note that calling functionsthat take parameters of type Any is still allowed.

  • —disallow-any-decorated
  • This flag disallows functions that have Any in their signatureafter decorator transformation.
  • —disallow-any-explicit
  • This flag disallows explicit Any in type positions such as typeannotations and generic type parameters.
  • —disallow-any-generics
  • This flag disallows usage of generic types that do not specify explicittype parameters. Moreover, built-in collections (such as list anddict) become disallowed as you should use their aliases from the typingmodule (such as List[int] and Dict[str, str]).
  • —disallow-subclassing-any
  • This flag reports an error whenever a class subclasses a value oftype Any. This may occur when the base class is imported froma module that doesn’t exist (when using—ignore-missing-imports) or isignored due to —follow-imports=skip or a# type: ignore comment on the import statement.

Since the module is silenced, the imported class is given a type of Any.By default mypy will assume that the subclass correctly inheritedthe base class even though that may not actually be the case. Thisflag makes mypy raise an error instead.