Type hints with forward reference: unresolved reference


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

Comment actions Permalink


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.

Comment actions Permalink

Hi, the project has hundreds of files. I made a new simple example project:


file: main.py

from mylib.parent import cParent
oParent = cParent("Daddy")


from mylib.child import cChild

class cParent():
def __init__(self,uParentName:str):
print ("Hello, I am a parent, my name is %s" % uParentName)
self.uParentName:str = uParentName
oChild = cChild(self,"Anna")

file: mylib/child.py:

class cChild():
def __init__(self,oParent:"mylib.parent.cParent", uChildName:str):
print ("Hello, I am a child, my name is %s, the name of my parent is %s" % (uChildName,oParent.uParentName))


folder structiure:


  ->  Folder mylib





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



Comment actions Permalink

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.

Comment actions Permalink

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


Comment actions Permalink

Forward references still require imports, they just allow you to mention e.g. a class inside itself. At least as I understand it.


Please sign in to leave a comment.