Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "missing" function in Python?

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 ?

like image 761
François M. Avatar asked Nov 28 '22 13:11

François M.


1 Answers

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')
like image 51
Willem Van Onsem Avatar answered Dec 09 '22 15:12

Willem Van Onsem