pythonfunctionmethodsparameters

How to programmatically determine if the default parameter value was used?


Given a function:

def foo(num = 42, bar = 100):
    print("num:", num)

How might I add code to foo to learn if foo was invoked with no argument for the num and/or bar parameters?


Solution

  • You might use decorator for unveiling what arguments were passed following way

    def show_arguments(func):
        def wrapper(*args, **kwargs):
            print('Positional arguments', args)
            print('Keyword arguments', kwargs)
            return func(*args, **kwargs)
        return wrapper
    
    
    @show_arguments
    def foo(num = 42, bar = 100):
        print("num:", num)
    
    
    foo()
    foo(1)
    foo(num=1)
    foo(1,bar=1)
    foo(num=1,bar=1)
    

    gives output

    Positional arguments ()
    Keyword arguments {}
    num: 42
    Positional arguments (1,)
    Keyword arguments {}
    num: 1
    Positional arguments ()
    Keyword arguments {'num': 1}
    num: 1
    Positional arguments (1,)
    Keyword arguments {'bar': 1}
    num: 1
    Positional arguments ()
    Keyword arguments {'num': 1, 'bar': 1}
    num: 1
    

    Observe that function in python are 1st class citizens.