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
Use this
def test( x, *args ):
Now you can do
test( x, 'one' )
and
test( x, 'one', 'two' )
and
test( x, *['one', 'two',] )
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With