Hinting type for type objects that are defined

I get an error message:

NameError: name 'OrgUnit' is not defined 
 class OrgUnit(object): def __init__(self, an_org_name: str, its_parent_org_unit: OrgUnit= None ): self.org_unit_name = an_org_name self.parent_org_unit = its_parent_org_unit def __str__(self): if self.parent_org_unit: parent_org_unit_name = self.parent_org_unit.__str__() return parent_org_unit_name + "->" + self.org_unit_name else: return self.org_unit_name if __name__ == '__main__': ibm_worldwide = OrgUnit("IBM_Worldwide") ibm_usa = OrgUnit("IBM_USA", ibm_worldwide) ibm_asia = OrgUnit("IBM_Asia", ibm_worldwide) ibm_china = OrgUnit("IBM_China", ibm_asia) print(ibm_worldwide) print(ibm_usa) print(ibm_asia) print(ibm_china) 

I am sure this is a well-known paradigm, since it seems to be a fairly common problem of using a hierarchical class (self-promotion class). I know that I can change its_parent_org_unit type as an object , and it works, but it seems to be wrong, primarily because it renounces my ability to check types in my calls. If its_parent_org_unit changed as an object type, I get the correct results:

 IBM_Worldwide IBM_Worldwide->IBM_USA IBM_Worldwide->IBM_Asia IBM_Worldwide->IBM_Asia->IBM_China 

I am open to thought and suggestions. What is the most "pythonic" way to do such things?

PS: What is the name of this kind of paradigm / self-defining class "self referencing class" that I could use to search for other suggestions?

+8
python class type-hinting
source share
1 answer

Your problem is that you want to use type hints, but you want this class to be able to accept arguments of its type.

The PEP hint types (0484) explain that you can use the lowercase version of the type name as a direct link . The example consists of a Tree data structure that seems surprisingly similar to this OrgUnit .

For example, this works:

 class OrgUnit(object): def __init__(self, an_org_name: str, its_parent_org_unit: 'OrgUnit' = None ): 
+14
source share

All Articles