Reputation: 11650
In Python, how can I check if *args[0] exists?
def my_fxn(self, *args):
print(args[0])
my_fxn('ABC') # this prints 'ABC'
my_fxn() # this crashes with "IndexError: tuple index out of range"
Upvotes: 3
Views: 15093
Reputation: 935
Another option is:
def my_fxn(self, *args):
arg0 = args and args[0] or False
# example results
# my_fxn('test', 'b', 12, 15) => 'test'
# my_fxn() => False
Not really sure how people feel about this type of overload though.
EDIT A quick explanation as to what is going on. When you look for args on its own it will evaluate to truthy if and only if there is something passed into args. This first test is required to prevent an IndexError: Index out of range error. If there IS something in args it will return the first argument (args[0]). This works even if the argument value in the first position is 'falsey' (f.e. 0, [], etc)
Upvotes: 2
Reputation: 11650
Just need to make sure args exists and has length of 1 or more. Same logic applies if you're looking for args[1]...args[n].
def my_fxn(self, *args):
if args and len(args) > 0:
print(args[0])
Edit:
Per Willem's comment len(args) > 0
is unnecessary if you're looking for args[0]
.
Upvotes: 0
Reputation: 476740
If you work with *args
, *args
will be a tuple (with zero, one or more elements). The truthiness of a tuple is True
if it contains at least one element. So you can simply write:
def my_fxn(self, *args):
if args:
print(args[0])
Upvotes: 5