reveal_type gives me a type, but it does not exist


So, I have a code that typechecks, but when I try to run it, it complains about the type not existing

import pyrsistent
a = pyrsistent.pset([1,2,3]) 
#reveal_type(a) #mypy, gives type pyrsistent.typing.PSet[]

#b : pyrsistent.typing.PSet[int] = a 
#when running: AttributeError: module 'pyrsistent' has no attribute 'typing'
#mypy does not complain, though

print ( a )

The line that fails is the assignment to the variable b (commented above)

How can I import the type, or anotate the code differently, to fix this problem?

Asked By: josinalvo



Just add import pyrsistent.typing to get access to that submodule:

import pyrsistent
import pyrsistent.typing

# To avoid the need to comment this call out; this will also print runtime type
from typing_extensions import reveal_type

a = pyrsistent.pset([1,2,3]) 
reveal_type(a) # N: revealed type is "pyrsistent.typing.PSet[]"

b: pyrsistent.typing.PSet[int] = a 


That’s usual thing to do with nested modules: you cannot just access them as attributes before import if they are not explicitly added in root of package.

mypy does not track this (not marking missing import/undefined symbol), because it’s too difficult to say whether any of your imported packages (including any other module you imported that could do import pyrsistent.typing – it can happen in any namespace, even without explicit import later) has already imported it. For example, the following:

import pyrsistent.typing

import pyrsistent
import a


will succeed, despite missing import on the first glance.

Answered By: SUTerliakov