1

This query is further with reference to this query

So, I am trying to execute the following code :

from collections import *

tp = namedtuple('emp', 'eid enames mob')
print(tp)
print(emp)

I can execute print(tp) and the output generated is <class '__main__.emp'>.

But when I try to execute print(emp), It generates the following exception :

Traceback (most recent call last):
  File "a.py", line 5, in <module>
    print(emp)
NameError: name 'emp' is not defined

What is the reason. The class emp is created. But I can not figure out how to access it directly. Or can I not ?

So basically, I can create instance of tp as tp() but not instances of emp in the same way. Why?

user3282758
  • 1,379
  • 11
  • 29

1 Answers1

0

Option 1: Just repeat the type name when assigning to the returned type

tp = emp = namedtuple('emp', 'eid enames mob')

Option 2: Use a declarative style instead of the functional APIs

from typing import NamedTuple

class emp(NamedTuple):
    eid: str
    enames: str
    mob: str
wim
  • 338,267
  • 99
  • 616
  • 750
  • I want to know what is the purpose of `emp` if I cannot use it. I have edited the question to reflect the same. – user3282758 Nov 12 '19 at 07:44
  • It is set as the name of the type. Check tp.__name__ – wim Nov 12 '19 at 07:50
  • you are right, `tp.__name__` does display `emp`. In fact if I create an object of `tp`, the `type(myobj)` shows type as `emp`. But I cannot use `emp` to create an object. Why is it so? – user3282758 Nov 12 '19 at 14:32
  • 1
    Because the name emp is unbound in your scope. You assigned the returned type to a different name. – wim Nov 12 '19 at 14:43