[Python-Dev] anonymous blocks

Alex Martelli aleaxit at yahoo.com
Wed Apr 20 04:07:45 CEST 2005

On Apr 19, 2005, at 15:57, BJörn Lindqvist wrote:

>> RSMotD (random stupid musing of the day): so I wonder if the decorator
>> syntax couldn't be extended for this kind of thing.
>> @acquire(myLock):
>>     code
>>     code
>>     code
> Would it be useful for anything other than mutex-locking? And wouldn't

Well, one obvious use might be, say:

@withfile('foo.bar', 'r'):
     content = thefile.read()

but that would require the decorator and block to be able to interact 
in some way, so that inside the block 'thefile' is defined suitably.

> it be better to make a function of the block wrapped in a
> block-decorator and then use a normal decorator?

 From a viewpoint of namespaces, I think it would be better to have the 
block execute in the same namespace as the code surrounding it, not a 
separate one (assigning to 'content' would not work otherwise), so a 
nested function would not be all that useful.  The problem might be, 
how does the _decorator_ affect that namespace.  Perhaps:

def withfile(filename, mode='r'):
     openfile = open(filename, mode)

i.e., let the block take keyword arguments to tweak its namespace (but 
assignments within the block should still affect its _surrounding_ 
namespace, it seems to me...).


More information about the Python-Dev mailing list