0

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?

Lecdi
  • 2,189
  • 2
  • 6
  • 20

1 Answers1

0

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)
The Fool
  • 16,715
  • 5
  • 52
  • 86
  • 1
    While this code may answer the question, it would be better to include some context, explaining _how_ it works and _when_ to use it. Code-only answers are not useful in the long run. – martineau Dec 19 '21 at 20:32