Macros in Python? (PEP 310)
Alex Martelli
aleax at aleax.it
Sat Apr 12 14:38:23 EDT 2003
More information about the Python-list mailing list
Sat Apr 12 14:38:23 EDT 2003
- Previous message (by thread): Macros in Python? (PEP 310)
- Next message (by thread): Macros in Python?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Dominic wrote:
>> def wrapfunc(func, pre=mkprint("hi"), post=mkprint("bye")):
>> def wrapped(*args, **kwds):
>> pre()
>> try: return func(*args, **kwds)
>> finally: post()
>> return wrapped
>
> Ups, I am surprised that wrapped still has access
> to func I thought that this would only work
> with Python's lambda. My fault.
Python's lambda gives *NO* extra power compared
with Python's named functions (except the ability
to keep functions unnamed, of course;-). And that
isn't your fault, but lambda's:-).
> The pre/post calls are only executed once
> when the file is loaded so this should be
> handled with care...
To be precise: the *default values* for pre
and post are computed exactly once in this
approach. The CALLS to pre and post are in
fact executed each time wrapped is executed.
> However I do not need to pass pre/post as
> parameters, so it does not matter very much.
OK, you can then hardcode them inside wrapped
rather than have them as parameters to wrapfunc
with default values.
> The only drawback is that the code needs
> to be separated into a fuction unless the
> generator "hack" is used. So wrapfunc seems
> to be the optimum so far.
Not sure what "generator hack" you're considering.
A generator is a function, so how would using a
generator save the need to "separate into a
function" the code to be wrapped? Not sure what
you mean by "separating" anyway -- you do need to
*NAME* the code, then pass the name you've chosen
to give -- and must take a modicum of care with
respect to bindings of local variables, which
become free variables (that a function can't
rebind in Python...) -- but basically the NAMING is
really the only "overhead" that would be avoidable
if Python had unnamed blocks (the scoping probably
would remain even WITH hypothetical unnamed blocks).
Alex
- Previous message (by thread): Macros in Python? (PEP 310)
- Next message (by thread): Macros in Python?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list