onekeystrokeatatime onekeystrokeatatime - 1 year ago 78
Python Question

Interpret input as string and class member name

In a few

of different classes I have to use several times the construct

self.member_name = kwargs['member_name']
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
and that the corresponding initialization gets produced. For example, if one inputs
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]
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 Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download