Pythonic way to check if a variable has been passed as kwargs?

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 with address.visibleor address.owner.

update_address(owner=None) must delete all existing owner objects.

What confuses me is how to determine if a string has been shown owner=None, so I know to delete the existing owner object, or if it was called without owner, set to everything, so that I leave the owner as it is.

+4
source share
3 answers

you can use the in keyword to check if there is a key, or you can specify a default parameter in the second argument of the get (key, default) function

if 'visible' in kwargs:
   do something

# OR

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

Update:

super() (.. ) , pop (key, default), . , .

def __init__(self, *args, **kwargs):
   visible = kwargs.pop('visible', False)
   super().__init__(*args, **kwargs)
+8

in keys:

if 'visible' in kwargs.keys():
    ...
+1

You can also make your own default option if it is more convenient; by creating an instance object, you can provide it different from anything else

no_parm = object() # this object is only used for default parms

def thisfunc( p = no_parm ):
    if p is no_parm:
         # default was used

def thatfunc(**kwargs):
    rateval = kwargs.get('rate', no_parm)
    if rateval is not no_parm:
        # it could be None, if the functiion wa called
        # as thatfunc( rate=None)
        #
        ...

Pay attention to the use isfor comparison - this is possible - and recommended - as we check to see if we have two references to the same object, and not to equality of values, as ==.

0
source

Source: https://habr.com/ru/post/1618614/


All Articles