Python NameError on custom TypeVar while being imported

51 Views Asked by At

I've tried to import generic type to other module, but to fail NameError: name 'AT' is not defined even though I've imported it.

I use python 3.8.10.

This is the directory structure:

├── aa
│   ├── aclass.py
│   └── __init__.py
├── bb
│   ├── bclass.py
│   └── __init__.py
└── test.py

Here's my code:

aclass.py

from typing import TypeVar, Type
from typing_extensions import Self
from abc import ABCMeta
from bb import *

AT = TypeVar('AT', bound='AClass')

class AClass(metaclass=ABCMeta):
    def __init__(self, a: int) -> None:
        self.a = a
        pass

    @classmethod
    def A_method(cls, a: Self, b: Self) -> Self:
        BC = BClass(a, b)
        return BC.B_method()


class ASub(AClass):
    ...
    # Other methods...


class ASub2(AClass):
    ...
    # Other methods...

_init_.py

from .aclass import ASub
from .aclass import ASub2
from .aclass import AT

__all__ = ['ASub', 'ASub2', 'AT']

bclass.py

from typing import Generic
from aa import *


class BClass(Generic[AT]):
    def __init__(self, a: AT, b: AT) -> None:
        self.a = a
        self.b = b
        pass

    def B_method(self) -> AT:
        i: int = self.a.a + self.b.a
        return ASub(i)

_init_.py

from .bclass import BClass

__all__ = ['BClass']

As you can see, I've imported aa package which has AT attribute. However, interpreter says AT is not defined:

Traceback (most recent call last):
  File "/home/jmg2027/workspace/test/test.py", line 1, in <module>
    from aa import *
  File "/home/jmg2027/workspace/test/aa/__init__.py", line 1, in <module>
    from .aclass import ASub
  File "/home/jmg2027/workspace/test/aa/aclass.py", line 7, in <module>
    from bb import *
  File "/home/jmg2027/workspace/test/bb/__init__.py", line 1, in <module>
    from .bclass import BClass
  File "/home/jmg2027/workspace/test/bb/bclass.py", line 5, in <module>
    class BClass(Generic[AT]):
NameError: name 'AT' is not defined

Here's my question. Is there any reason this happens? I'm facing this issue in much complex project, including circular import issue. The restriction: aclass.py should remain as it does.
How can I refactor my code not to experience this kind of problem?

0

There are 0 best solutions below