2

I'm trying to overload my functions by passing a single argument which might be a string or a list of strings. Whats the simplest way to end up with a list of strings?

>>> foo
'bar'
>>> bar
['foo', 'bar']

def myfunc(arg):
    listarg = list()
    listarg.extend(arg)
    print listarg

>>> myfunc(bar)
['foo', 'bar']
>>> myfunc(foo)
['b', 'a', 'r']

When I pass foo I want to see ['bar'].

I've fooled around with using isinstance(arg, str) or isinstance(arg, unicode) and isinstance(arg, collections.Iterable) but am not thrilled about them since the latter doesn't work and the former, well can't I just join to a list or something - I though str would do it but then unicode came along and am now afraid there might be more of them to test against.

John Mee
  • 50,179
  • 34
  • 152
  • 186
  • 1
    oh, look, now I find all the dups... http://stackoverflow.com/questions/9168904/ http://stackoverflow.com/questions/1055360/ http://stackoverflow.com/questions/836387/ Bit tragic if the best way to search is ask the question and look at the `related`s that it throws up! – John Mee Oct 17 '12 at 08:30
  • 1
    I would ask myself, why `foo` isn't `['bar']`. – phant0m Oct 17 '12 at 08:32

1 Answers1

2

In Python 2, str and unicode both derive from basestring.

Alas, in Python 3, there is no such common parent class. Here you shoud test for str and bytes.


def myfunc(arg):
    listarg = arg if not isinstance(arg, basestring) else [arg]
    print listarg

>>> myfunc(bar)
['foo', 'bar']
>>> myfunc(foo)
['bar']

>>> print sys.version
2.7.2 (default, Jun 20 2012, 16:23:33) 
John Mee
  • 50,179
  • 34
  • 152
  • 186
glglgl
  • 89,107
  • 13
  • 149
  • 217