Search code examples
pythontypingnamedtuple

Raising TypeError when creating a NamedTuple with typing


How can i make my named tuple to raise the TypeError exception?

from typing import NamedTuple

class Foo(NamedTuple):

    bar : int     
    sla : str

However when i try to create an instance of the namedtuple using invalid types no exception is raised

test = Foo('not an int',3)

#i can even print it

print(test.bar)
´´´

Solution

  • The typing module implements type hints, as defined in PEP 484. Type hints are exactly what the name implies...they are "hints". They don't affect the execution of Python code on their own. Per the PEP 484 document:

    While these annotations are available at runtime through the usual annotations attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter.

    So you need some additional code or tool to make use of the type information you've added to your code to either tell you beforehand that your code violates the type hints, or to tell you while the code is running. The typing module itself does not provide this functionality.

    I put your code in my PyCharm IDE, and the IDE flags the string parameter that you are passing to your constructor as in violation of the type hints, stating: "Expected type 'int', got 'str' instead". So the PyCharm IDE is one such tool that makes use of type hints. PyCharm is, however, quite happy to run the code and no errors are generated.