[Python-ideas] Allow "assigning" to Ellipse to discard values.

Andrew Barnert abarnert at yahoo.com
Tue Feb 10 23:44:34 CET 2015


On Feb 10, 2015, at 13:51, Chris Kaynor <ckaynor at zindagigames.com> wrote:

> On Tue, Feb 10, 2015 at 1:33 PM,  <random832 at fastmail.us> wrote:
>> Is cpython capable of noticing that the variable is never referenced (or
>> is only assigned) after this point and dropping it early? Might be a
>> good improvement to add if not.
> 
> I'm not sure that such would be viable in the general case, as
> assignment of classes could have side-effects. Consider the following
> code (untested):
> 
> class MyClass:
>    def __init__(self):
>        global a
>        a = 1
>    def __del__(self):
>        global a
>        a = 2
> 
> def myFunction():
>    b = MyClass() # Note that b is not referenced anywhere - it is
> local and not used in the scope or a internal scope.
>    print(a)
> 
> myFunction()
> 
> Without the optimization (existing behavior), this will print 1. With
> the optimization, MyClass could be garbage collected early (as it
> cannot be referenced), and thus the code would print 2 (in CPython,
> but it could also be a race condition or otherwise undetermined
> whether 1 or 2 will be printed).

Good point.

But does Python actually guarantee that a variable will be alive until the end of the scope even if never referenced?

That seems like the kind of thing Jython and PyPy would ensure for compatibility reasons even if it's not required (the same way, e.g., Jython ensures GIL-like sequential consistency on __setattr__ calls to normal dict-based classes), so it might be a bad idea to change it even if it's legal. But then it's more a practical question of how much working code would break, what the benefit is, etc.

Of course this same consideration also affects the original proposal. I can very easily write a class that does something that affects the global environment on __next__ but that's still a valid Sequence, so skipping the __next__ calls is even more dangerous than skipping the assignment...


More information about the Python-ideas mailing list