aiven
aiven

Reputation: 4323

how to extract type from class property (runtime type annotation check)?

from typing import NamedTuple

class A(NamedTuple):
    a: str
    b: int
    c = 0.432

How can I check whether a is a string?

I have already tried:

>> type(A.a)
property

Upvotes: 0

Views: 440

Answers (2)

chepner
chepner

Reputation: 532208

You need an instance of the class.

>>> type(A("foo", 3).a)
<class 'str'>

The str annotation is a type hint with no runtime meaning

>>> type(A(1,2).a)
<class 'int'>

so there is no sense in which A.a has a type of str; it's a property with a setter that will accept any value.

To get the type annotation at runtime:

>>> A.__annotations__['a']
<class 'str'>

Upvotes: 1

user2357112
user2357112

Reputation: 281843

namedtuple classes created with typing.NamedTuple have a _field_types attribute that stores a dict mapping field names to type annotations:

A._field_types['a']

Remember, this will give you annotations, which are quite likely to be things like 'str' (a string) or List[int] or other things incompatible with isinstance checks. Actually doing anything useful with the annotation may be harder than you expect.

Upvotes: 4

Related Questions