Reputation: 4278
In R, there is a missing()
function to test, quote : "whether a value was specified as an argument to a function" :
my_function <- function(argn1){
if(missing(argn1)){
print("argn1 has not been supplied")
} else {
print("argn1 has been supplied")
}
}
Then when calling :
my_function("hello")
[1] "argn1 has been supplied"
my_function()
[1] "argn1 has not been supplied"
Is there such a thing in Python ?
Upvotes: 4
Views: 7283
Reputation: 476574
Well usually arguments without a default value are mandatory. So you can provide a default object missing
for instance to check whether the attribute was given explicitly. Like:
missing = object()
def foo(arg1 = missing):
if arg1 is missing:
print('Arg1 is missing')
else:
print('Arg1 is not missing')
Using the is
over ==
can be of vital importance, since is
checks reference equality.
Sometimes one uses None
, like:
def foo(arg1 = None):
if arg1 is None:
# ...
But note that here Python cannot make a difference between an implicit argument, like foo()
or an explicit call with None
, like foo(None)
.
Furthermore there is also the option to use *args
:
def foo(*args):
# ...
If you call foo(None,1)
then all the arguments will be put into a tuple an that tuple is named args
(here args
will be args = (None,1)
). So then we can check if the tuple contains at least one element:
def foo(*args):
if args:
print('At least one element provided')
else:
print('No element provided')
Upvotes: 9
Reputation: 75
There is no obvious equivalent. But you can use default parameters.
def my_function(str=None):
if str is None:
print("argn1 has not been supplied")
else:
print("argn1 has been supplied")
Upvotes: 2
Reputation: 22598
In python, you will often find this kind of function declaration:
def my_function(arg1=None):
if arg1:
# Do something
else:
# Do something else
to achieve what you are looking for
Upvotes: 2
Reputation: 2682
No, there is no missing
function.
However, you can do the same thing by using function arguments with default values:
def foo(arg=None):
if arg is None:
print('arg is missing.')
else:
print('arg is present.')
Upvotes: 5
Reputation: 599540
No, because Python does not support calling a function with the wrong number of arguments. If you define a function to take one argument (without a default):
def my_func(arg1):
pass
and then call it just via my_func()
, Python will raise a TypeError.
Upvotes: 5