Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to know if the value of an argument is the default vs. user-specified?

I'm looking for something that works like Lisp's arg-supplied-p variables, to help differentiate a default value from the same value specified by a user.

Example:

def foo(a=10):
    pass

I'd like to know in foo if it was called like this:

foo()

or like this:

foo(10)

or even like this:

foo(a=10)

The last 2 are synonymous enough to me; I don't need to know that detail. I've looked through the inspect module a bit, but getargspec returns exactly the same results for all 3 calls.

like image 576
Gary Fixler Avatar asked Dec 01 '22 23:12

Gary Fixler


2 Answers

Except for inspecting the source code, there is no way to tell the three function calls apart – they are meant to have exactly the same meaning. If you need to differentiate between them, use a different default value, e.g. None.

def foo(a=None):
    if a is None:
        a = 10
        # no value for a provided
like image 101
Sven Marnach Avatar answered Dec 05 '22 01:12

Sven Marnach


As Sven points out, it's typical to use None for a default argument. If you even need to tell the difference between no argument, and an explicit None being provided, you can use a sentinel object:

sentinel = object()

def foo(a=sentinel):
    if a is sentinel:
        # No argument was provided
        ...
like image 34
Ned Batchelder Avatar answered Dec 05 '22 02:12

Ned Batchelder