Lazy Python usage (hack request)

Pearu Peterson pearu at ioc.ee
Sat Dec 30 14:04:23 CET 2000


Hi,

Is it possible to achive the following behavior in Python?

>>> import lazy
>>> a = b
No name 'b' defined, using default 777
>>> print a
777

Note that changing the python session above is not an option. (Also 'No'
for the answer;-)

Just to avoid questions 'Why do you need it?', I would use it in
PySymbolic (but not in its Kernel!) for defining new Symbol instances in
fly (it's very tedious to define 'b = Symbol("b")',etc all the time).

Here lazy.py would be something like the following:
#Begin of lazy.py

import UserDict,sys

class myDict(UserDict.UserDict):
    def __getitem__(self, key):
        if not self.data.has_key(key):
            print 'No name %s defined, using default 777'%(`key`)
            self.data[key] = 777
        return self.data[key]

sys.modules['__builtin__'].__dict__ = myDict(sys.modules['__builtin__'].__dict__)

#EOF lazy.py

When trying to set sys.modules['__builtin__'].__dict__, an exception
	TypeError: read-only special attribute
is raised.

Is there anyway to go around that? May be in C level?

Any hints, suggestions, or similar are appreciated.

Thanks,
	Pearu




More information about the Python-list mailing list