Type hints with forward reference: unresolved reference
Answered
Hi, just started to finally port my project to Python3 (3.7.4) and to use proper type hints.
I have one problem with forward references on type hints
I can import a class in a module by
from ORCA.definition.Definitions import cDefinitions
But when I try to use a forward reference in a type hint (in a module where I can't import cDefinitions)
class cDefinition:
def __init__(self,uDefinitionName:str, oDefinitions:'ORCA.definition.Definitions.cDefinitions'):
Pycharm flags an error "unresolved reference 'ORCA', when I run the "Inspect Code" routine
How to properly do a forward reference in such a case?
PyCharm 2019.2.1
Please sign in to leave a comment.
Hi,
Can you please provide a full code snippet to reproduce the issue? I'm afraid this small part of the code won't tell us anything.
Hi, the project has hundreds of files. I made a new simple example project:
file: main.py
file:mylib/parent.py
file: mylib/child.py:
folder structiure:
main.py
-> Folder mylib
__init__.py
parent.py
child.py
The error comes up on inspection of __init__ in cChild. The question is, how to apply a forward reference to cParent, as you can't import cParent
Thanks
Hi Carstenthielepape, that's not really a PyCharm issue but a type annotation system limitation in Python. Meanwhile, there are some tricks to workaround this case, please see the relevant mypy recommendation https://mypy.readthedocs.io/en/latest/common_issues.html#import-cycles Basically you need to add an import under the if clause so a type checker (either mypy or PyCharm) will be able to resolve the reference while the runtime will skip it.
Hi Pavel,
I have understood (and maybe I am wrong) that type annotation with forward references have been introduced to Python 3.7 (and I should adjust my example, to add those forward references as a string). The difference to the mypy example is, that I am using a python source which is in a folder and not in the root folder. I haven't such a limitation in the PEP for type annotations
Forward references still require imports, they just allow you to mention e.g. a class inside itself. At least as I understand it.