tags:

views:

473

answers:

6

I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.

Given that strings act as lists of characters, how do I tell which the method has received?

I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).

Python version is 2.5

A: 

Have you considered varargs syntax? I'm not really sure if this is what you're asking, but would something like this question be along your lines?

David Berger
Wouldn't that just force the caller to specify which was being sent? I'd prefer to avoid that if possible. (And I'm also intrigued as to whether what I want to do is possible in an elegant way...)
mavnn
+3  A: 

You can use type function

>>> type('/dev/null')
<type 'str'>
>>> type(['/dev', '/null'])
<type 'list'>
>>> type('/dev/null') is str
True
>>> type(['/dev', '/null']) is str
False
>>> type('/dev/null') is list
False
>>> type(['/dev', '/null']) is list
True
Daniel Ribeiro
+6  A: 

You can check if a variable is a string or unicode string with

isinstance(some_object, basestring)

This will return True for both strings and unicode strings

Edit:

You could do something like this:

if isinstance(some_object, basestring):
    ...
elif all(isinstance(item, basestring) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
    ...
else:
    raise TypeError # or something along that line

Stringness is probably not a word, but I hope you get the idea

Steef
Aha! I thought there must be some common ancestry somewhere, I just couldn't find the reference...
mavnn
+2  A: 

Check the type with isinstance(arg, basestring)

Ants Aasma
+1  A: 

Type checking:

def func(arg):
    if not isinstance(arg, (list, tuple)):
        arg = [arg]
    # process

func('abc')
func(['abc', '123'])

Varargs:

def func(*arg):
    # process

func('abc')
func('abc', '123')
func(*['abc', '123'])
FogleBird
A: 

isinstance is an option:

In [2]: isinstance("a", str)
Out[2]: True

In [3]: isinstance([], str)
Out[3]: False

In [4]: isinstance([], list)
Out[4]: True

In [5]: isinstance("", list)
Out[5]: False
Renato Besen