Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python required variable style

Tags:

python

What is the best style for a Python method that requires the keyword argument 'required_arg':

def test_method(required_arg, *args, **kwargs):


def test_method(*args, **kwargs):
    required_arg = kwargs.pop('required_arg')
    if kwargs:
        raise ValueError('Unexpected keyword arguments: %s' % kwargs)

Or something else? I want to use this for all my methods in the future so I'm kind of looking for the best practices way to deal with required keyword arguments in Python methods.

like image 664
Adam Nelson Avatar asked Jul 10 '26 01:07

Adam Nelson


2 Answers

The first method by far. Why duplicate something the language already provides for you?

Optional arguments in most cases should be known (only use *args and **kwargs when there is no possible way of knowing the arguments). Denote optional arguments by giving them their default value (def bar(foo = 0) or def bar(foo = None)). Watch out for the classic gotcha of def bar(foo = []) which doesn't do what you expect.

like image 193
Yann Ramin Avatar answered Jul 11 '26 13:07

Yann Ramin


The first method offers you the opportunity to give your required argument a meaningful name; using *args doesn't. Using *args is great when you need it, but why give up the opportunity for clearer expression of your intent?

like image 42
Pierce Avatar answered Jul 11 '26 14:07

Pierce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!