user130076
user130076

Reputation:

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?

Upvotes: 2

Views: 2349

Answers (5)

nosklo
nosklo

Reputation: 222862

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)

Upvotes: 10

mouad
mouad

Reputation: 70031

You can also do this while keeping the if test:

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

Upvotes: 0

Thomas
Thomas

Reputation: 6762

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.

Upvotes: 1

phimuemue
phimuemue

Reputation: 35983

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.

Upvotes: 1

Zach
Zach

Reputation: 19082

if isinstance(item, list):

Upvotes: 3

Related Questions