[Python-Dev] defmacro (was: Anonymous blocks)

Jim Jewett jimjjewett at gmail.com
Fri Apr 22 23:36:19 CEST 2005

As best I can tell, the anonymous blocks are used to take 
care of boilerplate code without changing the scope -- exactly 
what macros are used for.  The only difference I see is that in 
this case, the macros are limited to entire (possibly compound) 

To make this more concrete,

>>     in synchronized(the_lock):
>>         BODY

Nick Coghlan:
> s/in/with/ to get PEP 310.

>Guido's recent screed crystallised the idea of writing resources
> as two-part generators:

[Adding Reinhold Birkenfeld's suggestion of a blank yield]

> def my_resource():
>    print "Hi!"     # Do entrance code
>    yield           # Go on with the contents of the 'with' block
>    print "Bye!"    # Do exit code

The macro itself looks reasonable -- so long as there is only 
ever one changing block inside the macro.  I'm not sure that 
is a reasonable restriction, but the alternative is ugly enough 
that maybe passing around locals() starts to be just as good.

What about a block that indicates the enclosed namespaces
will collapse a level?

defmacro myresource(filename):
    <make explicit calls to named callback "functions", but 
      within the same locals() scope.>

with myresource("thefile"):
    def reader(): 
    def writer():
    def fn():

Then myresource, reader, writer, and fn would share a
namespace without having to manually pass it around.


More information about the Python-Dev mailing list