Python: Return tuple or list?

后端 未结 3 736
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 03:33

I have a method that returns either a list or a tuple. What is the most pythonic way of denoting the return type in the argument?

def names(self, section, as_typ         


        
3条回答
  •  北海茫月
    2021-02-20 04:12

    The pythonic way would be not to care about the type at all. Return a tuple, and if the calling function needs a list, then let it call list() on the result. Or vice versa, whichever makes more sense as a default type.

    Even better, have it return a generator expression:

    def names(self, section):
        return (m[0] for m in self.items(section))
    

    Now the caller gets an iterable that is evaluated lazily. He then can decide to iterate over it:

    for name in obj.names(section):
        ...
    

    or create a list or tuple from it from scratch - he never has to change an existing list into a tuple or vice versa, so this is efficient in all cases:

    mylist = list(obj.names(section))
    mytuple = tuple(obj.names(section))
    

提交回复
热议问题