0

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?

  • 2
    `type` gets the information from within the object. `isinstance` needs the class that it needs to check against which is not available in its scope. – rdas Sep 07 '22 at 15:16
  • @rdas Ah, makes sense, thanks! Is there a recommended way to validate the type if I'm feeding the namedtuple into a new function down the pipeline? It seems natural to define the type within the initial function, but I s'pose I should define it outside the function if other functions need access to it for type checking? – dewser_the_board Sep 07 '22 at 15:53

0 Answers0