Search code examples
pythonmethodsdefault-value

How to recognize default method value setting in Python?


Consider the following class method definition in Python using default parameter values:

class X
..

    def batch(self, param="foobar", limit=2):
    ...

Then, a user could call it without arguments, just like

x.batch()

Result: the parameter values get substituted with default values.

Imagine in such case you would like to tell the user something like:

WARNING the batch size has been set to a default value 2.

Question: is there a way to backtrack either somehow intercept to recognize it (beyond simply moving this initialization and validation logic to a constructor method)?


Solution

  • You can't detect when the default value is being used, but perhaps something like this?

    import warnings
    
    
    class X
    ..
    
        def batch(self, param="foobar", limit=None):
            if limit == None:
                limit = 2
                warnings.warn(...)
    
        ...