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_type=()):
return type(as_type)(([m[0] for m in self.items(section)]))
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
Now the caller gets an iterable that is evaluated lazily. He then can decide to iterate over it:
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: