Type Hinting for objects of type that’s being defined [duplicate]

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:

class OrgUnit(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

class OrgUnit(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.

Leave a Comment