开发者

Python - Neaten this append/extend conditional

I have a method which I will accept either a single object or a list of objects. I want to add whatever is passed to another list. Currently, my method looks like this:

def appendOrExtend(self, item):
  if type(item).__name__ == "list":
    self.list.extend(item)
  else:
    self.list.append(item)

It seems to me that there should be 开发者_开发百科a more Pythonic way of achieving this, could you suggest one?


def append(self, item):
    self.list.append(item)
def extend(self, item):
    self.list.extend(item)

Bottom line: Don't have a method to do both things. It confuses and makes your method less useful, instead of more useful. It's also harder to test and to maintain. Also the user of your function already knows if she wants to use append or extend, so by providing a single method you're discarding the information your caller/user already knows.

Another way to write is using packing/unpacking argument syntax:

def append(self, *items):
    self.list.extend(items)

that way you can call the method as

x.append('single item')

or

x.append(*list_of_items)


if isinstance(item, list):


Zach provides a solution for checking the type more elegant. However, I would introduce two separate methods addOneElement and addMoreElements (or something similar). This makes it - in my eyes - much more readable.


If you want to be able to handle sets and tuples, you might add those. To be really flexible, maybe you should take anything iterable, but then risk confusion by strings or other objects that you want taken individually but happen to be iterable. Soon someone will tell you that this is a Bad Idea, and they will probably be right - this much flexibility in your interface makes it ambiguous.


You can also do this while keeping the if test:

if not isinstance(item, list):
    item = [item]
self.list.extend(item)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜