Python: Quick and dirty datatypes (DTO)

后端 未结 6 1761
孤城傲影
孤城傲影 2021-02-12 10:22

Very often, I find myself coding trivial datatypes like

class Pruefer:
    def __init__(self, ident, maxNum=float(\'inf\')         


        
6条回答
  •  天涯浪人
    2021-02-12 11:03

    One of the most promising things from with Python 3.6 is variable annotations. They allow to define namedtuple as class in next way:

    In [1]: from typing import NamedTuple
    
    In [2]: class Pruefer(NamedTuple):
       ...:     ident: int
       ...:     max_num: int
       ...:     name: str
       ...:     
    
    In [3]: Pruefer(1,4,"name")
    Out[3]: Pruefer(ident=1, max_num=4, name='name')
    

    It same as a namedtuple, but is saves annotations and allow to check type with some static type analyzer like mypy.

    Update: 15.05.2018

    Now, in Python 3.7 dataclasses are present so this would preferable way of defining DTO, also for backwardcompatibility you could use attrs library.

提交回复
热议问题