[Python-ideas] local variable access : __getlocal__ and __setlocal__

Pierre-Yves Martin pym.aldebaran at gmail.com
Sun Feb 18 21:16:59 CET 2007


Currently it's possible to customize attribute access via methods :

__getattribute__(self, name)
__getattr__(self, name)
__setattr__(self, name, value)


but it is not possible to customize local variable access. It would be
useful for example to allow implementation of a local constant or any other
on-access/on-modification behavior. The function should could be:

__getlocal__(name)
__setlocal__(name, value)

By default they are just access to the local dictionnary for reading and
writting (AFAIK the only current way to access this dictionnary is using the
locals()  built-in).
Here is a sample code of typical usage :

#######################
#Sample 1 : Tracing local access

old_getlocal = __getlocal__
old_setlocal = __setlocal__

#redefine the built-ins
def __getlocal__(name):
    print 'accessing %s' % name
    return old_getlocal(name)

def __setlocal__(name, value):
    print 'setting %s with value %s' % (name, value)
    old_setlocal(name, value)

a = 1
b = 2
c = 3

#setting b and accessing  a
b = a + 1

###################
#Sample 2 : Constants
old_getlocal = __getlocal__
old_setlocal = __setlocal__
class ConstantError(Exception):pass
constants = []

#redefine the built-ins
def __setlocal__(name, value):
    if old_getlocal(name, value) in constants:
        raise ConstantError()
    else:
        old_setlocal(name, value)

a = 1
b = 2
c = 3

constants = [b, c]

a = 4 #OK
b = 5 #IMPOSSIBLE

constant.remove(c)

c = 6 #OK


I found such approach more flexible than introducing a 'const' in python
(not a good thing I think). And it enable many other customizations...

Note : the fact that in my example I DO NOT access to any kind of writable
local dictionary! This on purpose, the only way to access this dictionary
should be : locals(), __getlocal__() and __setlocal__() built-ins.

Pierre-Yves Martin
pym<dot>aldebaran< a t >gmail<dot>com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20070218/7a3c26c6/attachment.html>


More information about the Python-ideas mailing list