NamedTuple - сhecking types of fields at runtime

172 Views Asked by At

Is there a neat solution to raise an error if a value is passed to the NamedTuple field that does not match the declared type?

In this example, I intentionally passed page_count str instead of int. And the script will work on passing the erroneous value forward.

(I understand that linter will draw your attention to the error, but I encountered this in a case where NamedTuple fields were filled in by a function getting values from config file).

I could check the type of each value with a condition, but it doesn't look really clean. Any ideas? Thanks.

from typing import NamedTuple

class ParserParams(NamedTuple):

    api_url: str
    page_count: int
    timeout: float

parser_params = ParserParams(
    api_url='some_url',
    page_count='3',
    timeout=10.0,
)
1

There are 1 best solutions below

2
jurez On

By design, Python is a dynamically typed language which means any value can be assigned to any variable. Typing is only supported as hints - the errors might be highlighted in your IDE, but they do not enforce anything.

This means that if you need type checking you have to implement it yourself. On the upside, this can probably be automated, i.e. implemented only once instead of separately for every field. However, NamedTuple does not provide such checking out of the box.