Search code examples
pythondefaultkeyword-argument

How to check at function call if default keyword arguments are used


I`m working on some initialization function/method which should warn you if the default values are used for the kwargs. I can't figure out how to do so and google did not help me either. Any solutions?

To illustrate

class MyClass():
    def __init__(a=0,b=1):
        ''' Should warn you if using default.'''
        self._a = a
        self._b = b

Should act as follows

MyClass(a=1)
>>> 'warning: default b=1 is used.

Why would one want the warning: Defualts are there to illustrate the typical values used. However the end user should set them and not be lazy(!). End user manipulates yamls with kwargs: make end user aware if he/she messes up. Basically I want the (soft) requiredness of args with all the benefits of kwargs.


Solution

  • Use kwargs in __init__ for the warnings and then a dedicated initialize function for the assignment of the variables:

    class MyClass():
        def __init__(self, **kwargs):
            defaults = dict(a=0, b=1)
            for key,val in defaults.items():
                if key not in kwargs:
                    print("warning: default {}={} is used.".format(key, val))
                kwargs[key]=val
    
            self.initialize(**kwargs)
    
        def initialize(self, a=0, b=1):
            self._a = a
            self._b = b
    
    MyClass()
    print('-'*50)
    MyClass(a=5)
    print('-'*50)
    MyClass(a=4,b=3)
    

    The output is:

    warning: default b=1 is used.
    warning: default a=0 is used.
    --------------------------------------------------
    warning: default b=1 is used.
    --------------------------------------------------