开发者

kwargs parsing best practice

开发者 https://www.devze.com 2023-02-24 09:49 出处:网络
Is there a more compact/efficient way of doing this? for key in kwargs: if key == \'log\': self.log = kwargs[key]

Is there a more compact/efficient way of doing this?

    for key in kwargs:
        if key == 'log':
            self.log = kwargs[key]
        elif key == 'bin':
            self.bin = kwargs[key]
        elif key == 'pid':
            self.pid 开发者_如何学运维= kwargs[key]
        elif key == 'conf':
            self.conf = kwargs[key]


To achieve exactly what you asked for, you could use

for key in ('log', 'bin', 'pid', 'conf'):
    if key in kwargs:
        setattr(self, key, kwargs[key])

or

self.__dict__.update((key, kwargs[key])
                     for key in ('log', 'bin', 'pid', 'conf')
                     if key in kwargs)

However, I would generally prefer something like this:

def f(log=None, bin=None, pid=None, conf=None):
    self.log = log
    self.bin = bin
    self.pid = pid
    self.conf = conf

While this is still somewhat repetitive, the code is really easy to read. All attributes are intialized regardles of whether the corresponding keyword argument is passed in, and the signature of the function clearly documents the arguments and there defaults.


self.log = kwargs.get('log', default_log)
self.bin = kwargs.get('bin', default_bin)
self.pid = kwargs.get('pid', default_pid)
self.conf = kwargs.get('conf', default_conf)

This has the additional advantage that self.log is assigned in any case (AttributeError means your code is broken as hell, nothing more. Always make sure everything is always assigned.). Without extra self.log = default_log lines. You can omit the default to get None.


If the key provided in get() is not in the dictionary the result is None.

self.log = kwargs.get('log')
self.bin = kwargs.get('bin')
self.pid = kwargs.get('pid')
self.conf = kwargs.get('conf')


for k,v in kwarg.iteritems():
   setattr(self, k, v)

In which setattr(self, "bin", "val") is like calling self.bin = "val"

However it is more desirable to have a whitelist like @Sven Marnach has.


for k,v in kw.items():
   setattr(self, k, v)


self.__dict__.update(kwargs)


My solution for this is:

for key in ('log', 'bin', 'pid', 'conf'):
    setattr(self, key, kwargs.get(key, None))

In this mode, all attributes are initialized.

When I have a large number of attributes, I prefer to create a list to be easier to read like this:

kwargs_list = [
    "log",
    "bin",
    "pin",
    "conf"
]

for key in kwargs_list:
    setattr(self, key, kwargs.get(key, None))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号