__getattr__ functionality for modules?

Troels Therkelsen t_therkelsen at hotmail.com
Mon May 19 07:07:52 EDT 2003


In article <k85gcvgdg7lgldmnrq88gqgmdmla9r0q5l at 4ax.com>, Stefan Franke wrote:
> On 18 May 2003 18:55:20 -0400, aahz at pythoncraft.com (Aahz) wrote:
> ...
>>Nope, and Guido is violently opposed to making this possible.  Why not
>>just use a class?
> 
> Because a namespace object behaves different when it comes to setting
> attributes: There are no nested scopes. 
> 
> What I'm trying to realize is a small domain specific configuration 
> language: A subset of Python that consists of nothing else but 
> 
> - a couple of functions,
> 
> - the ability to define your own functions with 'def' with correct scope nesting
> 
> - Python's numeric expressions
> 
> - and an (unlimited) number of builtin constants. That's what I need
>   the module getattr hook for
> 
> This is absolutely trivial to learn for the users in my context. Using
> objects and attributes here adds an unnecessary (and unwanted)
> level of complexity.
> 

This is a wild shot, but maybe what you're looking for is the so-called
sandbox functionality?  There used to be a (buggy) module for it called
rexec, but for various reasons it is no longer part of the official 
standard lib of v2.3.

A small demonstration:

Python 2.3b1 (#1, Apr 27 2003, 22:07:38) 
[GCC 2.95.3 20010315 (release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> sandbox = {'__builtins__':{}}
>>> sandbox['a'] = 42
>>> exec 'print a' in sandbox
42
>>> exec 'print len("foo")' in sandbox
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1, in ?
NameError: name 'len' is not defined

The latter fails because the __builtins__ dict in the sandbox doesn't
contain the name 'len'... we can add Python builtins thus:

>>> import __builtin__
>>> sandbox['__builtins__']['len'] = __builtin__.len 
>>> exec 'print len("foo")' in sandbox
3

The eval() and execfile() builtins can operate on a custom namespace dict,
too.  

Hope this helps,

Troels Therkelsen





More information about the Python-list mailing list