nnja nnja - 5 months ago 19
Python Question

Modify different objects without checking flags

I am wanting to modify different objects. At the moment I pass a flags parameter to decide whether to perform the changes or not. Is there a way to make this work without passing any flags, or is this the best way of doing it? I dont feel like this is a scalable solution once I have more instances of the objects.

def modifyfunc(self, flags, id_to_modify, value):
if flags['object1']:
self.object1.modify(id_to_modify, value)
if flags['object2']:
self.object2.modify(id_to_modify, value)
if flags['object3']:
self.object3.modify(id_to_modify, value)


Note that flags can be true for any
objectx
. Assume that any objectx implements the
modify
method correctly (basically, the object instances are of different types that inherit from the same base class, so they all have the method
modify
but may be implemented differently between these objects).

Answer

Using getattr, you can access arbitrary instance member of an object:

getattr(obj, instance_attribute_name)

Example:

>>> 'a'.upper()
'A'
>>> getattr('a', 'upper')()
'A'

Instead of flags, how about pass names of attribute to modify?

def modifyfunc(self, attr_names, id_to_modify, value):
    for attr_name in attr_names:
        getattr(self, attr_name).modify(id_to_modify, value)

...

obj.modifyfunc(['object1', 'object3'], 'id1', 'value1')