Accessing global namespace

Jeff Epler jepler at unpythonic.net
Tue Oct 7 07:57:13 EDT 2003


On Mon, Oct 06, 2003 at 08:09:52PM -0700, Dave Benjamin wrote:
> Jeff Epler wrote:
> 
> >I'd say you're better off writing something like this:
> >
> >    def attr_reader(name):
> >        def get(self):
> >            return getattr(self, "_" + name)
> >        return property(get)
> >
> >    class Benjamin(object):
> >        _a = 42
> >        a = attr_reader('a')
> >
> >    t = Benjamin()
> >    print t.a
> 
> True, but with the "exec" version, you could implement attr_accessor, 
> too (getter and setter), as well as write a version that works like this:

def attr_accessor(name, validator):
	def get(self):
		return getattr(self, "_" + name)

	def set(self, value):
		setattr(self, "_" + name, value)

	return property(get, set)

> exec attr_reader('a', 'b', 'c')

def attr_reader_star(*names):
	return [attr_reader(name) for name in names]
a, b, c = attr_reader('a', 'b', 'c')

The optimizing compiler, if it was written, should also hoist the
getattr() and setattr() calls to LOAD_ATTR and STORE_ATTR calls:
it will be forbidden to shadow builtins, so the optimizer can replace
getattr() and setattr() with more efficient bytecode sequences if
possible.  Second, it can notice that 'name' is immutable and never
rebound.  Third, it can notice that "_" + name is also a constant
expresion.  Now, the optimizer has enough informtaion to transform the
getattr() expression into a LOAD_ATTR instruction.

Jeff





More information about the Python-list mailing list