onekeystrokeatatime onekeystrokeatatime - 13 days ago 7
Python Question

Interpret input as string and class member name

In a few

__init__
of different classes I have to use several times the construct

try:
self.member_name = kwargs['member_name']
except:
self.member_name = default_value


or as suggested by Moses Koledoye

self.member_name = kwargs.get('member_name', default_value)


I would like to have a method that inputs, say, the string
'member_name'
and
default_value
and that the corresponding initialization gets produced. For example, if one inputs
'pi_approx'
and
3.14
the resulting code is

self.pi_approx = kwargs.get('pi_approx', 3.14)


In this way I can replace a long sequence of these initializations by a loop along a list of all the required members and their default values.

This technique emulate a switch statement is not the same thing but kind of has a similar flavor.

I am not sure how to approach what I want to do.




Assuming that
initializer(m_name, default_val)
is the construction that gets replaced by

self.m_name = kwargs.get('m_name', default_val)


I would then used it by having a lists
member_names = [m_name1, m_name2, m_name3]
and
default_values = [def_val1, def_val2, def_val3]
and calling

for m_name, d_val in zip(member_names, default_values):
initializer(m_name, d_val)


This would replace long list of try's and also make the code a bit more readable.

Answer

If your try/except was meant to handle KeyError, then you can use the get method of the kwargs dict which allows you to supply a default value:

self.member_name = kwargs.get('member_name', default)

Which can be extended to your list of attribute names using setattr:

for m_name, d_val in zip(member_names, default_values):
    setattr(self, m_name, kwargs.get(m_name, d_val))
Comments