profile
viewpoint

Ask questionsIssues with conditional imports

Even though #649 was closed, there still remains several issues related to conditional imports. This issue is a top-level issue for these.

Related, more specific issues:

  • #591
  • #1107
  • #1153
  • #1026
python/mypy

Answer questions rodrigc

@JukkaL While introducing mypy to the CI for the Twisted codebase, I ran into this problem which is similar to the examples mentioned in this issue, similar to the one brought up by @ethanhs:

https://github.com/twisted/twisted/pull/1261#discussion_r421875636

What is the way to deal with this:

try:
    from foo import A
except ImportError:
    A = None

Is there something that needs to be fixed in mypy? For now, I just put:

A = None # type:ignore

to turn off mypy errors on that line. As much as possible, I want to avoid turning off mypy like that.

The other option is to follow the example mentioned by @cjerdonek here: https://github.com/python/mypy/issues/1297#issuecomment-508593494

and do:

try:
   from foo import A as _A
except ImportError:
   A = None
else:
   A = _A
useful!

Related questions

mypy not inferring that variable cannot be None after assignment from dict.get hot 1
Dynamic base classes hot 1
Using mypy with mixins and abstract properties hot 1
--disallow-untyped-calls allows calling values with Any type hot 1
Variable assignment on module reference reported as "Module has no attribute <variable_name>" hot 1
mypy checks parent package's init, even though child directory is specified hot 1
--disallow-untyped-calls allows calling values with Any type hot 1
--disallow-untyped-calls allows calling values with Any type hot 1
segmentation fault on indexing object with __getattr__ hot 1
Allow use of type variables at runtime hot 1
type alias to union is invalid in runtime context hot 1
Function line number information is not always correct hot 1
Github User Rank List