Python: Return tuple or list?

后端 未结 3 831
被撕碎了的回忆
被撕碎了的回忆 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 03:51

    Keep it simple:

    def names(self, section):
        """Returns a list of names."""
        return [m[0] for m in self.items(section)]
    

    If the caller wants a tuple instead of a list, he does this:

    names = tuple(obj.names(section))
    

提交回复
热议问题