getattr

Recursively access dict via attributes as well as index access?

Recursively access dict via attributes as well as index access? Question: I’d like to be able to do something like this: from dotDict import dotdictify life = {‘bigBang’: {‘stars’: {‘planets’: []} } } dotdictify(life) # This would be the regular way: life[‘bigBang’][‘stars’][‘planets’] = {‘earth’: {‘singleCellLife’: {}}} # But how can we make this work? life.bigBang.stars.planets.earth …

Total answers: 5

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

How do I call setattr() on the current module? Question: What do I pass as the first parameter “object” to the function setattr(object, name, value), to set variables on the current module? For example: setattr(object, “SOME_CONSTANT”, 42); giving the same effect as: SOME_CONSTANT = 42 within the module containing these lines (with the correct object). …

Total answers: 4

__getattr__ on a module

__getattr__ on a module Question: How can implement the equivalent of a __getattr__ on a class, on a module? Example When calling a function that does not exist in a module’s statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same …

Total answers: 8

How do I override __getattr__ in Python without breaking the default behavior?

How do I override __getattr__ without breaking the default behavior? Question: How do I override the __getattr__ method of a class without breaking the default behavior? Asked By: sheats || Source Answers: Overriding __getattr__ should be fine — __getattr__ is only called as a last resort i.e. if there are no attributes in the instance …

Total answers: 3

What is the relationship between __getattr__ and getattr?

What is the relationship between __getattr__ and getattr? Question: I know this code is right: class A: def __init__(self): self.a = ‘a’ def method(self): print “method print” a = A() print getattr(a, ‘a’, ‘default’) print getattr(a, ‘b’, ‘default’) print getattr(a, ‘method’, ‘default’) getattr(a, ‘method’, ‘default’)() And this is wrong: # will __getattr__ affect the getattr? …

Total answers: 3

How do I implement __getattribute__ without an infinite recursion error?

How do I implement __getattribute__ without an infinite recursion error? Question: I want to override access to one variable in a class, but return all others normally. How do I accomplish this with __getattribute__? I tried the following (which should also illustrate what I’m trying to do) but I get a recursion error: class D(object): …

Total answers: 6