views:

58

answers:

5

Hey,

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 acheiving this, could you suggest one?

Cheers,

Pete

+2  A: 
if isinstance(item, list):
Zach
I really asking if there is a way to do away with the entire if/else conditional than how to test for a list, but thank you.
Peter
+1 `isinstance(item, list)` seems to me much more pythonic than `type(item).__name__ == "list"`
eumiro
+1  A: 

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.

phimuemue
+1  A: 

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.

Thomas
+6  A: 
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)
nosklo
+1: "Don't have a method to do both things"
S.Lott
A: 

You can also do this while keeping the if test:

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