[Python-Dev] anonymous blocks
Steven Bethard
steven.bethard at gmail.com
Thu Apr 21 18:20:50 CEST 2005
James Y Knight wrote:
> If it was possible to assign to a variable to a variable bound outside
> your function, but still in your lexical scope, I think it would fix
> this issue. That's always something I've thought should be possible,
> anyways. I propose to make it possible via a declaration similar to
> 'global'.
>
> E.g. (stupid example, but it demonstrates the syntax):
> def f():
> count = 0
> def addCount():
> lexical count
> count += 1
> assert count == 0
> addCount()
> assert count == 1
It strikes me that with something like this lexical declaration, we
could abuse decorators as per Carl Banks's recipe[1] to get the
equivalent of thunks:
def withfile(filename, mode='r'):
def _(func):
f = open(filename, mode)
try:
func(f)
finally:
f.close()
return _
and used like:
line = None
@withfile("readme.txt")
def print_readme(fileobj):
lexical line
for line in fileobj:
print line
print "last line:" line
As the recipe notes, the main difference between print_readme and a
real "code block" is that print_readme doesn't have access to the
lexical scope. Something like James's suggestion would solve this
problem.
One advantage I see of this route (i.e. using defs + lexical scoping
instead of new syntactic support) is that because we're using a normal
function, the parameter list is not an issue -- arguments to the
"thunk" are bound to names just as they are in any other function.
The big disadvantage I see is that my normal expectations for
decorators are wrong here -- after the decorator is applied
print_readme is set to None, not a new callable object.
Guess I'm still riding the fence. ;-)
STeVe
[1]http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/391199
--
You can wordify anything if you just verb it.
--- Bucky Katt, Get Fuzzy
More information about the Python-Dev
mailing list