Type Hinting For Objects Of Type That's Being Defined
I get the error: NameError: name 'OrgUnit' is not defined class OrgUnit(object): def __init__(self, an_org_name: str, its_parent_org_unit: O
Solution 1:
Your problem is that you want to use type hints but you want this class itself to be able to take arguments of its own type.
The type hints PEP (0484) explains that you can use the string version of the type's name as a forward reference. The example there is of a Tree
data structure which sounds remarkably similar to this OrgUnit
one.
For example, this works:
classOrgUnit(object):
def__init__(self,
an_org_name: str,
its_parent_org_unit: 'OrgUnit' = None):
In Python 3.7, you will be able to activate postponed evaluation of annotations with from __future__ import annotations
. This will automatically store annotations as strings instead of evaluating them, so you can do
from __future__ import annotations
classOrgUnit(object):
def__init__(self,
an_org_name: str,
its_parent_org_unit: OrgUnit= None):
...
This is scheduled to become the default in Python 4.0.
Post a Comment for "Type Hinting For Objects Of Type That's Being Defined"