Macros in Python? (PEP 310)
oblivious at web.de
Sun Apr 13 09:05:41 CEST 2003
> Not sure what "generator hack" you're considering.
From Beni (a previous posting):
>>To complete the list of solutions, there is an evil way to abstract
>>try..finally that is not recommended due to it's unreadability to
>>anybody that doesn't know the trick. It also only works in CPython
>>with reference counting that invokes __del__ immediately.
>>The basic idea was to use a for loop and a generator:
>> oldid = geteuid()
>> yield None # dummy
>>for _ in with_root_privs: # `_` is dummy
>> # Dohere whatever you wanted. The generator will cause this to be
>> # executed exactly once, with pre- and post- code excuted...
^^^^^^^^ The code needs not to be written into a function,
that's what I tried to say with "separate".
>>The problem, of course is that the for loop's body can raise an
>>exception, or exit the loop in other evil ways. Luckily in CPython,
>>exiting the loop immediately drops the only reference to the
>>generator, so hooking it's __del__ would do the trick. Writing it as
>>an iterator class instead of a generator would be be ugly but we can
>>only do it once, by a universal wrapper taking a naive generator and
>>returning a safe one. Google for "abstracting try..finally with
>>generators" in c.l.py if you are interested. Again, it's hard to
>>recommend this hack. Instead, consider pushing PEP 310 .
Thank you very much for your detailed answers Alex :-)
More information about the Python-list