mohRamadan
mohRamadan

Reputation: 639

Python nested classes gives `undefined name`

I've a main class with 2 nested classes:

class cls_1:
  
  class Enum_1(Enum):
     ...
  
  @dataclass
  class Nested:
     ...
     feature: Enum_1 #NameError: name 'Enum_1' is not defined

As you can see I'm using one of the nested classes as type in another nested class. But this gives: NameError: name 'Enum_1' is not defined as highlighted in the code.

I feel I'm missing something obvious but not sure what's that.

Upvotes: 1

Views: 502

Answers (1)

Robin Gugel
Robin Gugel

Reputation: 1206

The problem is that values defined in the class-definition scope are not available in the inner scopes of that class.

class A:
    class B:
        pass
    
    def foo(self):
        print(B) # doesn't work
        print(A.B) # does work

For functions this is obvious, as you always need to access class attributes through the instance, but as the code inside a function is an extra scope inside the class another class definition is also an inner scope - where you don't have the names in that are in the outer class defined (hope all that made sense like that...) See resolution of names in the docs

Well - to solve your problem you need to access the Enum through cls_1:

Edit: But sadly in that case you have the problem that cls_1 doesn't exist at that point. So you'd need to set the annotation into quotes so it's not executed. Typecheckers will understand the annotations that way though.

class cls_1:
  
  class Enum_1(Enum):
     ...
  
  @dataclass
  class Nested:
     ...
     feature: "cls_1.Enum_1"

Upvotes: 2

Related Questions