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

Chris Kaynor ckaynor at zindagigames.com
Tue Feb 10 22:51:04 CET 2015


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).

I'm not saying that it is a good idea to write such a class, but a
change to how variables are assigned would be backwards-incompatible,
and could result in very odd behavior in somebody's code.

Chris


More information about the Python-ideas mailing list