Reputation: 165
So I want to create a function and have it perform differently based on the type of the parameter passed in. Specifically I want it to do one thing if a string is entered, and something else if a list is entered. Is this possible in Python? And if so how would I go about doing it?
At the moment I've tried using isinstance() but it doesn't seem to be hitting any of my if statements:
def tester(*args):
if (isinstance(args, str)):
return "String"
elif (isinstance(args, list)):
return"List"
else:
return "You dun goofed"
EDIT: The user will only ever be passing in one argument at a time, either a list or a string.
Upvotes: 0
Views: 225
Reputation: 2358
Looks like all you would be passing is a single argument to your function. In that case remove the '*' since it is always considered as a tuple of arguments. It is variable-length arguments and is to be used when you aren't sure of the number of arguments that you function would need.
def tester(args):
if (isinstance(args, str)):
return "String"
elif (isinstance(args, list)):
return"List"
else:
return "You dun goofed"
If your function actually requires variable length parameters and you want to check whether the first parameter being passed is a string or a list, you can do:
def tester(*args):
if (isinstance(args[0], str)):
return "String"
elif (isinstance(args[0], list)):
return"List"
else:
return "You dun goofed"
Upvotes: 2
Reputation: 133534
*args
is the tuple of arguments passed to the argument. The splat (*
) operator unpacks the arguments given in the function call eg.
>>> def tester(*args):
print args
print type(args)
>>> tester(1, 'a')
(1, 'a')
<type 'tuple'>
So what you probably want to do is check isinstance
on each of the args and make sure they are all str
or list
for example:
if all(isinstance(a, str) for a in args):
Upvotes: 3