Carlos Adir
Carlos Adir

Reputation: 472

Python Decorator to force passing arguments explicitly

I have a function that can receive 3 arguments. Only X is mandatory and I could write this function like

def foo(X, A=None, B=None):
    pass

But I want to force the user to call this function passing explicitly the arguments

foo(X=1, A=2, B=3)
foo(1, 2, 3)  # Error

Is it possible make a decorator for that?

@explicitarguments
def foo(X, A=None, B=None):
    pass

Upvotes: 2

Views: 234

Answers (2)

clarkmaio
clarkmaio

Reputation: 399

You can also write a decorator that raise and error when args are passed as input.

In this way you can even raise a specific error in case you need to catch this kind of error in a potential try/expect framework.

def explicitarguments(func):
    '''Simple decorator to enforce user to use only keyword'''

    def wrapper(*args, **kwargs):
        if args:
            raise RuntimeError('You can not pass arguments without keyword')
        return func(*args, **kwargs)
    return wrapper

Upvotes: 0

timgeb
timgeb

Reputation: 78650

If you can modify the function definition, refer to this question.

A minimal decorator to patch existing functions looks like this:

def explicitarguments(f):
    def f_new(**kwargs):
        return f(**kwargs)        
    return f_new

Upvotes: 4

Related Questions