Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to check if a variable was passed as kwargs?

Tags:

python

django

visible = models.BooleanField()
owner = models.ForeignKey(User, null=True)

def update_address(**kwargs):
    address = Address.objects.get(address=kwargs.get('address'))
    try:
        address.visible = kwargs.get('visible')
    except:
        pass
    try:
        address.owner = kwargs.get('owner')
    except:
        pass

update_address() should result in nothing happening to address.visible or address.owner.

update_address(owner=None) should delete whatever existing owner object was set.

The thing that's confusing me is how to tell if owner=None was explicitly set so I know to delete the existing owner object, or if it was called without owner set to anything so I should leave the owner as it is.

like image 751
davidtgq Avatar asked Dec 04 '15 16:12

davidtgq


2 Answers

you can use the "in" keyword to check if the key is there or you can specify the default param in the second argument of the dict.get(key, default) function

if 'visible' in kwargs:
   do something

# OR

visible = kwargs.get('visible', False) 

Update:

if your super() class (ie the parent model) doesn't take the visible param, you can use the dict.pop(key, default) to extract the param before passing it to the super. I thought this could be useful for you to know as well.

def __init__(self, *args, **kwargs):
   visible = kwargs.pop('visible', False)
   super().__init__(*args, **kwargs)
like image 173
Du D. Avatar answered Sep 19 '22 09:09

Du D.


You could use in and keys:

if 'visible' in kwargs.keys():
    ...
like image 27
Gocht Avatar answered Sep 21 '22 09:09

Gocht