I have the following code:
In [38]: %paste
def set_session_attribute(obj, attribute):
if attribute.endswith('()'):
attribute = attribute.replace('()', '')
return getattr(obj, attribute)()
else:
return getattr(obj, attribute)
class Thing(object):
def __init__(self):
self.legs = 4
def length(self):
return 6
## -- End pasted text --
In [39]: x = Thing()
In [40]: y = set_session_attribute(x, 'legs')
In [41]: y
Out[41]: 4
In [42]: z = set_session_attribute(x, 'length()')
In [43]: z
Out[43]: 6
This is because calling with "length()"
didn't work (AttributeError, no attribute length()
)
Is there a shorter, more maintainable way to make functions like this? Thank you.