Search code examples
pythonpython-typingpython-dataclassesnamedtuple

Type hints in namedtuple


Consider following piece of code:

from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))

The Code above is just a way to demonstrate as to what I am trying to achieve. I would like to make namedtuple with type hints.

Do you know any elegant way how to achieve result as intended?


Solution

  • The preferred syntax for a typed namedtuple since Python 3.6 is using typing.NamedTuple like so:

    from typing import NamedTuple
    
    class Point(NamedTuple):
        x: int
        y: int = 1  # Set default value
    
    Point(3)  # -> Point(x=3, y=1)
    

    Starting with Python 3.7, consider using a dataclasses:

    from dataclasses import dataclass
    
    @dataclass
    class Point:
        x: int
        y: int = 1  # Set default value
    
    Point(3)  # -> Point(x=3, y=1)