Type hints in namedtuple

前端 未结 2 1560
误落风尘
误落风尘 2020-12-04 18:54

Consider following piece of code:

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

The Code above i

相关标签:
2条回答
  • 2020-12-04 19:02

    You can use typing.NamedTuple

    From the docs

    Typed version of namedtuple.

    >>> import typing
    >>> Point = typing.NamedTuple("Point", [('x', int), ('y', int)])
    

    This is present only in Python 3.5 onwards

    0 讨论(0)
  • 2020-12-04 19:25

    The prefered Syntax for a typed named tuple since 3.6 is

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

    Edit Starting Python 3.7, consider using dataclasses (your IDE may not yet support them for static type checking):

    from dataclasses import dataclass
    
    @dataclass
    class Point:
        x: int
        y: int = 1  # Set default value
    
    Point(3)  # -> Point(x=3, y=1)
    
    0 讨论(0)
提交回复
热议问题