1

I need to define a custom data structure (say, Exp) which can have fields as same data structure (i.e., Exp) but very confused what to use...

I'm using NamedTuple in Python3 but when defining the field of type same structure, get Errors.

from typing import NamedTuple

class Expression(NamedTuple):
    left: Expression
    right: Expression
    operator: str

exp = Expression(None, None, "AS")
print(exp)

this generates error as follows:

Traceback (most recent call last):
  File "expression.py", line 3, in <module>
    class Expression(NamedTuple):
  File "expression.py", line 4, in Expression
    left: Expression
NameError: name 'Expression' is not defined
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 1
    The problem here isn't really the use of `NamedTuple`, but trying to make the type hint work, when the type needs to be recursive (self-referential). It happens because Python is trying to understand the type hint for `left`, before it has finished creating the `Expression` type. The linked duplicate should give you the information you need to make that work. – Karl Knechtel Oct 21 '19 at 08:22
  • that's not what I was asking... you should remove that duplicate... – Gaurav Goswami Oct 21 '19 at 08:54
  • The *only* thing preventing your code from working is the type hint. The approach in the duplicate should make it work. If you don't care about type hints, then you can just as easily use `collections.namedtuple`. If you do, then you need to use a forward reference for the type, as explained in the duplicate. – Karl Knechtel Oct 21 '19 at 22:36

0 Answers0