Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single string or list of strings in a method [duplicate]

Tags:

python

I have run into this several times. I'm dealing with a lot of methods that can accept a list of strings. Several times I have accidentally passed a single string and it gets broken apart into a list and each character is used, which isn't the desired behavior.

def test(a,b):
    x = []
    x.extend(a)
    x.extend(b)
    return x

x = [1,2,3,4]

What I don't want to happen:

test(x,'test')
[1, 2, 3, 4, 't', 'e', 's', 't']

I have to resort to a strange syntax:

test(x,['list']) 

I would like these to work implicitly:

test(x,'list')
[1, 2, 3, 4, 'test']

test(x,['one', 'two', 'three'])
[1, 2, 3, 4, 'one', 'two', 'three']

I really feel like there's a "pythonic" way to do this or something involving duck typing, but I don't see it. I know I could use isinstance() to check if it's a string, but I feel like there's a better way.

Edit: I'm using python 2.4.3

like image 712
shadowland Avatar asked Oct 20 '11 15:10

shadowland


2 Answers

Use this

def test( x, *args ):

Now you can do

test( x, 'one' )

and

test( x, 'one', 'two' )

and

test( x, *['one', 'two',] )
like image 82
S.Lott Avatar answered Oct 21 '22 08:10

S.Lott


From The Zen of Python:

Explicit is better than implicit.

In my opinion, your first example is explicit. It takes two values and processes them in well-understood ways. Although it "feels" a little strange to new Python programmers, it behaves just like expect. list.extend accepts lists, so it treats strings like a list of chars.

Your proposal alters the semantics of list.extend to be equivalent to list.append, but only when dealing with strings. That would be a real surprise to someone who wants your function to treat your strings as lists of chars and who would then have to call it like test(x,list('test')).

You can do what you're asking, but please don't. :-)

like image 24
Kirk Strauser Avatar answered Oct 21 '22 06:10

Kirk Strauser