getattr and setattr on nested subobjects / chained properties?

You could use functools.reduce: import functools def rsetattr(obj, attr, val): pre, _, post = attr.rpartition(‘.’) return setattr(rgetattr(obj, pre) if pre else obj, post, val) # using wonder’s beautiful simplification: https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects/31174427?noredirect=1#comment86638618_31174427 def rgetattr(obj, attr, *args): def _getattr(obj, attr): return getattr(obj, attr, *args) return functools.reduce(_getattr, [obj] + attr.split(‘.’)) rgetattr and rsetattr are drop-in replacements for getattr and … Read more

How can I dynamically create class methods for a class in python [duplicate]

You can dynamically add a classmethod to a class by simple assignment to the class object or by setattr on the class object. Here I’m using the python convention that classes start with capital letters to reduce confusion: # define a class object (your class may be more complicated than this…) class A(object): pass # … Read more

Using setattr() in python

The Python docs say all that needs to be said, as far as I can see. setattr(object, name, value) This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, … Read more

How to use __setattr__ correctly, avoiding infinite recursion

You must call the parent class __setattr__ method: class MyTest(object): def __init__(self, x): self.x = x def __setattr__(self, name, value): if name==”device”: print “device test” else: super(MyTest, self).__setattr__(name, value) # in python3+ you can omit the arguments to super: #super().__setattr__(name, value) Regarding the best-practice, since you plan to use this via xml-rpc I think this … Read more

How do I call setattr() on the current module?

import sys thismodule = sys.modules[__name__] setattr(thismodule, name, value) or, without using setattr (which breaks the letter of the question but satisfies the same practical purposes;-): globals()[name] = value Note: at module scope, the latter is equivalent to: vars()[name] = value which is a bit more concise, but doesn’t work from within a function (vars() gives … Read more

How do I use getattr and setattr properly in Python? [closed]

The second argument to getattr and setattr are strings that name the attribute you want. That is, getattr(name, “expected_grade”). Using a variable as the second argument means that the value of the variable is used as the name. Generally, though, there is no real difference between name.expected_grade and getattr(name, ‘expected_grade’), although you can supply getattr … Read more