, , .
, , :
def write_to_device(args):
try:
args = list(args)
except TypeError:
args = [args]
print args
, , :
>>> write_to_device(1)
[1]
>>> write_to_device([1,2])
[1, 2]
>>> write_to_device('abc')
['a', 'b', 'c']
You can fix this by using isinstanceto check if the argument is a string:
def write_to_device(args):
if isinstance(args, basestring):
args = [args]
else:
try:
args = list(args)
except TypeError:
args = [args]
print args
What gives you:
>>> write_to_device(1)
[1]
>>> write_to_device([1,2])
[1, 2]
>>> write_to_device('abc')
['abc']
As someone noted, you can let your function accept an arbitrary number of arguments:
def write_to_device(*args):
print args
What you need:
>>> write_to_device(1)
(1,)
>>> write_to_device([1,2])
([1, 2],)
>>> write_to_device('abc')
('abc',)
>>> write_to_device(*[1,2])
(1, 2)
My recommended way is to simply require the list to be passed to the function:
write_to_device([1])
write_to_device([1, 2, 3])
It is simple, straightforward and unambiguous.