Reputation: 7949
I want to keep my type aliases in one module, say my_types
, to be able to
use them anywhere in my application (similar to the standard typing
module).
But mypy complains that the forward reference to class X
is not defined.
If I define class X
later in that same module, it’s okay, but if it defined
in another one, mypy gets upset.
So my question is, how do I keep all my type aliases in one module without mypy producing an error about forward references that are not defined in the same module? Or is that a wrong approach somehow?
Here is my example code:
from my_types import SomeXs
class X:
pass
Type aliases are defined like so:
# my_types.py
from typing import List
SomeXs = List['X']
When I run mypy, I get an error that X
is not defined:
$ mypy module.py
my_types.py:4: error: Name 'X' is not defined
Found 1 error in 1 file (checked 1 source file)
Upvotes: 6
Views: 3005
Reputation: 7949
I’m gonna share the solution I found in the mypy documentation common issues section here: It is necessary for mypy to have access to the definition of X
. To avoid an import cycle, the mypy
documentation recommends a trick - only import the definition that
would create a cyclic import when type checking. It goes like this:
from typing import List, TYPE_CHECKING
if TYPE_CHECKING:
from main import X
SomeXs = List['X']
This makes the Python interpreter ignore the import when executing
this code, but mypy still uses the definition of X
from main
.
Et voilá:
$ mypy *.py
Success: no issues found in 2 source files
Upvotes: 12
Reputation: 58908
Mypy needs to have referenced types in scope:
$ cat my_types.py
from typing import List
from main import X
SomeXs = List[X]
And the code containing X
doesn't reference SomeXs
, so it shouldn't be imported there:
$ cat main.py
class X:
pass
The result:
$ mypy .
Success: no issues found in 2 source files
Upvotes: 0