How To Check If A Key in **kwargs Exists?

后端 未结 6 2003
孤街浪徒
孤街浪徒 2020-12-13 03:09

Python 3.2.3. There were some ideas listed here, which work on regular var\'s, but it seems **kwargs play by different rules... so why doesn\'t this work and how can I check

6条回答
  •  有刺的猬
    2020-12-13 03:39

    One way is to add it by yourself! How? By merging kwargs with a bunch of defaults. This won't be appropriate on all occasions, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:

    import sys
    
    def myfunc(**kwargs):
        args = {'country':'England','town':'London',
                'currency':'Pound', 'language':'English'}
    
        diff = set(kwargs.keys()) - set(args.keys())
        if diff:
            print("Invalid args:",tuple(diff),file=sys.stderr)
            return
    
        args.update(kwargs)            
        print(args)
    

    The defaults are set in the dictionary args, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args with kwargs which will overwrite any new values that the user has set. We don't need to test if a key exists, we now use args as our argument dictionary and have no further need of kwargs.

提交回复
热议问题