Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clunky arg check in Python

I have a function:

def check_user(self, **args):
    allowed = ['name', 'screen_name', 'url', 'description', 'location']
    arg_check = [val for val in args if val not in allowed]
    if arg_check:
        raise ValueError('Invalid args: ' + ' '.join(arg_check))

And it works, but it feels very unpythonic. Is there a better way of checking this? I was hoping to not have to write a big if/else statement.

This way I can iterate over the args in a loop easily.

like image 650
polkid Avatar asked Jul 25 '26 23:07

polkid


1 Answers

I think a more pythonic version would explicitly declare the allowed arguments in the function definition. Just replace None with your default values.

def check_user(self, name=None, screen_name=None, url=None,
               description=None, location=None):
    # Do something here
    # ...
like image 75
FastTurtle Avatar answered Jul 28 '26 12:07

FastTurtle



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!