If a namedtuple
is defined within a function, is it possible to use isinstance()
to check the type of the namedtuple
outside of the function.
I'm surprised that I'm able to use type()
to get the type, but the isinstance()
function fails.
Example:
from collections import namedtuple
def parse_a(raw_string):
Parsed_A = namedtuple("Parsed_A", "attr1,attr2")
p = [x.strip() for x in raw_string.split(",")]
return Parsed_A(attr1=p[0], attr2=p[1] if len(p) > 1 else None)
parsed_a = parse_a("thing1,thing2")
print(f'{type(parsed_a)=}')
print(f'{isinstance(parsed_a, Parsed_A)=}')
In the above, the type()
function accurately returns the type, but the isinstance()
function fails with a NameError, presumably due to the namedtuple
being defined in a different scope.
Why is the type()
function successful while the isinstance()
fails?