[Python-ideas] Assignments in list/generator expressions

Nick Coghlan ncoghlan at gmail.com
Sun Apr 10 14:10:00 CEST 2011


On Sun, Apr 10, 2011 at 8:37 PM, Arnaud Delobelle <arnodel at gmail.com> wrote:
> The only (but big!) problem is that this deletes any previously defined variable "x", "f", and "d" in the current scope.  So why not just rename the variables "x", "f", and "d" at compile time to something that is guaranteed not to appear elsewhere in the scope, e.g. "@1", "@2", "@3" or some other naming scheme, in the style of the old "gensym" function in Lisp?

I considered a strategy along those lines when eliminating the leakage
of the scope variables for list comprehensions in Py3k and it turns
out to be rather painful from a nested scopes point of view. It's not
*impossible*, of course, but you end up having to manage this parallel
pseudo-namespace inside the real one and it rapidly becomes an
absolute mess (as you have to implement a second copy of most of the
nested scopes logic in order to handle closures correctly and you will
curse the existence of the locals() function).

The compiler can't see inside the strings used to look up values via
"locals()", so there's no way to adjust them to handle the automatic
renaming. If you "lift" a class or function out of a statement local
namespace, there's also the question of what the value of the __name__
attribute ends up being.

I have updated the torture test accordingly, it now includes a third
example that renaming strategies will have serious problems handling:

   y = y given:
       x = 42
       def f(): pass
       y = locals("x"), f.__name__
   assert "x" not in locals()
   assert "f" not in locals()
   assert y == (42, "f")

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list