__getattr__ for static/class variables

__getattr__() and __str__() for an object are found on its class, so if you want to customize those things for a class, you need the class-of-a-class. A metaclass. class FooType(type): def _foo_func(cls): return ‘foo!’ def _bar_func(cls): return ‘bar!’ def __getattr__(cls, key): if key == ‘Foo’: return cls._foo_func() elif key == ‘Bar’: return cls._bar_func() raise AttributeError(key) … Read more

Understanding the difference between __getattr__ and __getattribute__

Some basics first. With objects, you need to deal with their attributes. Ordinarily, we do instance.attribute. Sometimes we need more control (when we do not know the name of the attribute in advance). For example, instance.attribute would become getattr(instance, attribute_name). Using this model, we can get the attribute by supplying the attribute_name as a string. … Read more

Recursively access dict via attributes as well as index access?

Here’s one way to create that kind of experience: class DotDictify(dict): MARKER = object() def __init__(self, value=None): if value is None: pass elif isinstance(value, dict): for key in value: self.__setitem__(key, value[key]) else: raise TypeError(‘expected dict’) def __setitem__(self, key, value): if isinstance(value, dict) and not isinstance(value, DotDictify): value = DotDictify(value) super(DotDictify, self).__setitem__(key, value) def __getitem__(self, key): … 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 implement __getattribute__ without an infinite recursion error?

You get a recursion error because your attempt to access the self.__dict__ attribute inside __getattribute__ invokes your __getattribute__ again. If you use object‘s __getattribute__ instead, it works: class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name==’test’: return 0. else: return object.__getattribute__(self, name) This works because object (in this example) is the base class. By … Read more

__getattr__ on a module

There are two basic problems you are running into here: __xxx__ methods are only looked up on the class TypeError: can’t set attributes of built-in/extension type ‘module’ (1) means any solution would have to also keep track of which module was being examined, otherwise every module would then have the instance-substitution behavior; and (2) means … Read more

What is getattr() exactly and how do I use it?

Objects in Python can have attributes — data attributes and functions to work with those (methods). Actually, every object has built-in attributes (try dir(None), dir(True), dir(…), dir(dir) in Python console). For example you have an object person, that has several attributes: name, gender, etc. You access these attributes (be it methods or data objects) usually … Read more