Solution: Re: Lazy Python usage (hack request)
Pearu Peterson
pearu at cens.ioc.ee
Sat Dec 30 19:56:00 EST 2000
Hi again,
I have implemented a Python C/API module `lazy' that you can use to put a
Python dictionary to a "lazy" mode.
You can find the lazy module in
http://cens.ioc.ee/~pearu/misc/lazy-0.1.tar.gz
Here is a Python session showing lazy in action:
>>> import lazy
>>> d = {'a':4}
>>> lazy.set(d,lambda k:3) # set d to lazy mode
>>> print d
{'_lazy_cb': <function <lambda> at 0x8112e24>, 'a': 4}
>>> d['b']
3
>>> print d
{'_lazy_cb': <function <lambda> at 0x8112e24>, 'b': 3, 'a': 4}
>>> del d['_lazy_cb'] # disable lazy mode
>>> d['c']
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: c
And another example:
>>> import lazy
>>> def fun(k):
... print 'Creating variable %s'%(`k`)
... return k
...
>>> lazy.set(locals(),fun)
>>> print a+b+c
Creating variable 'a'
Creating variable 'b'
Creating variable 'c'
abc
>>> print lazy.set.__doc__
lazy.set(dict,func) - set dictionary dict to a "lazy" mode with
a callback function func.
"lazy" mode means that the following statement
dict[<name>] = func(<name>)
is executed whenever dict has no key <name>.
WARNING: if dict is set to "lazy" mode, dict.has_key(<name>)
returns always 1 and dict[<name>] is set to func(<name>).
To disable the "lazy" mode for dict, do
del dict['_lazy_cb']
Be lazy and have fun!-)
Pearu
More information about the Python-list
mailing list