Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python typing allow object of a certain class in the __init__ of that same class

I am trying to create a class called Theme whose __init__ function allows another object, which may be of type Theme, to be passed in. But when I try and type hint that an object of that type is allowed, Python throws an error because Theme is not yet defined. Here is the code, which works when I take out the type hint:

from typing import Union


class Theme:

    def __init__(self, start: Union[dict, Theme, None] = None):
        if start is None:
            start = {}
        elif isinstance(start, Theme):
            start = start.dict
        self.dict = start

The error I am getting is:

Traceback (most recent call last):
  File "C:/Users/.../Test.py", line 4, in <module>
    class Theme:
  File "C:/Users/.../Test.py", line 6, in Theme
    def __init__(self, start: Union[dict, Theme, None] = None):
NameError: name 'Theme' is not defined

Is there any way I can achieve this or is it just not possible and I shouldn’t bother?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can import annotations from __future__. I think in 3.10 this is available by default.

from __future__ import annotations

from typing import Optional


class MyClass:
    def __init__(self, cls: Optional[MyClass]) -> None:
        if cls:
            print(isinstance(cls, MyClass))


c = MyClass(None)
b = MyClass(c)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading