Python: Quick and dirty datatypes (DTO)

后端 未结 6 1753
孤城傲影
孤城傲影 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 10:52

    I don't have much to add to the already excellent answer by Alexey Kachayev -- However, one thing that may be useful is the following pattern:

    Pruefer.__new__.func_defaults = (1,float('inf'),"")
    

    This would allow you to create a factory function which returns a new named-tuple which can have default arguments:

    def default_named_tuple(name,args,defaults=None):
        named_tuple = collections.namedtuple(name,args)
        if defaults is not None:
            named_tuple.__new__.func_defaults = defaults
        return named_tuple
    

    This may seem like black magic -- It did to me at first, but it's all documented in the Data Model and discussed in this post.

    In action:

    >>> default_named_tuple("Pruefer", "ident maxNum name",(1,float('inf'),''))
    
    >>> Pruefer = default_named_tuple("Pruefer", "ident maxNum name",(1,float('inf'),''))
    >>> Pruefer()
    Pruefer(ident=1, maxNum=inf, name='')
    >>> Pruefer(3)
    Pruefer(ident=3, maxNum=inf, name='')
    >>> Pruefer(3,10050)
    Pruefer(ident=3, maxNum=10050, name='')
    >>> Pruefer(3,10050,"cowhide")
    Pruefer(ident=3, maxNum=10050, name='cowhide')
    >>> Pruefer(maxNum=12)
    Pruefer(ident=1, maxNum=12, name='')
    

    And only specifying some of the arguments as defaults:

    >>> Pruefer = default_named_tuple("Pruefer", "ident maxNum name",(float('inf'),''))
    >>> Pruefer(maxNum=12)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: __new__() takes at least 2 arguments (2 given)
    >>> Pruefer(1,maxNum=12)
    Pruefer(ident=1, maxNum=12, name='')
    

    Note that as written, It's probably only safe to pass a tuple in as defaults. However, you could easily get more fancy by ensuring you have a reasonable tuple object within the function.

提交回复
热议问题