getattr

Calling types via their name as a string in Python

I'm aware of using globals(), locals() and getattr to referance things in Python by string (as in this question) but unless I'm missing something obvious I can't seem to use this with calling types. e.g.: In [12]: locals()['int'] --------------------------------------------------------------------------- KeyError ...

Python: Convert string into function name; getattr or equal?

I am editing PROSS.py to work with .cif files for protein structures. Inside the existing PROSS.py, there is the following functions (I believe that's the correct name if it's not associated with any class?), just existing within the .py file: ... def unpack_pdb_line(line, ATOF=_atof, ATOI=_atoi, STRIP=string.strip): ... ... def read_pd...

Jython 2.1 __getattr__

I am trying to implement a wrapper/proxy class for a java object (baseClient) in jython v2.1. Everything seems to be working ok except when the following statement is encountered: if __client != None # __client is an instance of the ClientProxy class raise AttributeError(attr) is called in __getattr__(), because self.__baseClient does...

JavaScript: Version of __defineGetter__ that allows access to the attr you're trying to access?

I've been looking for a replacement for Python's __getattr__ in JavaScript, and a couple answers here mentioned Firefox's __defineGetter__. Not only is that not cross-browser compatible but it doesn't really allow for you to do anything really useful like this pseudo-code does: var api = function() { var __getattr__ = function(attr,...

Why does the "name" parameter to __setattr__ include the class, but __getattr__ doesn't?

The following code: class MyClass(): def test(self): self.__x = 0 def __setattr__(self, name, value): print name def __getattr__(self, name): print name raise AttributeError(name) x = MyClass() x.test() x.__y Outputs: _MyClass__x __y Traceback (most recent call last): ... AttributeError:...

Is it bad practice to use python's getattr extensively?

I'm creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making use of the fact that functions are first class objects in python. For flexibility's sake (mostly for parsing commands), I'm thinking of changing my setup such that I'm...

Calling a method with getattr in Python

How to call a method using getattr? I want to create a metaclass, which can call non-existing methods of some other class that start with the word 'oposite_'. The method should have the same number of arguments, but to return the opposite result. def oposite(func): return lambda s, *args, **kw: not oposite(s, *args, **kw) class ...

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

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). I'm generate several values at th...

Python: Recursively access dict via attributes as well as index access?

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.e...

__getattr__ for static/class variables in python

I have a class like: class MyClass: Foo = 1 Bar = 2 Whenever MyClass.Foo or MyClass.Bar is invoked, I need a custom method to be invoked before the value is returned. Is it possible in Python ? I know it is possible if I create an instance of the class and I can define my own __getattr__ method. But my scnenario involves usi...

Python Chain getattr as a string

import amara def chain_attribute_call(obj, attlist): """ Allows to execute chain attribute calls """ splitted_attrs = attlist.split(".") current_dom = obj for attr in splitted_attrs: current_dom = getattr(current_dom, attr) return current_dom doc = amara.parse("sample.xml") print chain_attribute_call(...

Querying for entities with missing properties in app engine Datastore?

I have a model which looks like this: class Example (db.Model) : row_num = db.IntegerProperty(required=True) updated = db.IntegerProperty() ... ... Now when i store values, I may not fill the value for the updated property every time, which implies that in some entities it may not exist. I want to construct a datastore query so ...

Pythonic solution to my reduce getattr problem

I used to use reduce and getattr functions for calling attributes in a chain way like "thisattr.thatattr.blaattar" IE: reduce(getattr, 'xattr.yattr.zattr'.split('.'), myobject) Works perfectly fine, however now I have a new requirement, my strings can call for a specific number of an attribute as such: "thisattr.thatattr[2].blaattar" ...

Asymmetric behavior for __getattr__, newstyle vs oldstyle classes

Hi, this is the first time I write here, sorry if the message is unfocuessed or too long. I was interested in understanding more about how objects'attributes are fetched when needed. So I read the Python 2.7 documentation titled "Data Model" here, I met __getattr__ and, in order to check whether I understood or not its behavior, I wro...

Python, using two variables in getattr?

I'm trying to do the following: import sys; sys.path.append('/var/www/python/includes') import functionname x = 'testarg' fn = "functionname" func = getattr(fn, fn) func (x) but am getting an error: "TypeError: getattr(): attribute name must be string" I have tried this before calling getattr but it still doesn't work: str(fn) ...

Python's getattr gets called twice?

I am using this simple example to understand Python's getattr function: In [25]: class Foo: ....: def __getattr__(self, name): ....: print name ....: ....: In [26]: f = Foo() In [27]: f.bar bar bar Why is bar printed twice? Using Python 2.6.5. ...

Python, Django, how to use getattr (or other method) to call object that has multiple attributes?

After trying to get this to work for a while and searching around I am truly stumped so am posting here... I want to make some functions in classes that I am writing for django as generic as possible so I want to use getattr to call functions such as the one below in a generic manner: the way I do it that works (non-generic manner): fr...

__getattr__ equivalent for methods

When an attribute is not found object.__getattr__ is called. Is there an equivalent way to intercept undefined methods? ...