Can python optimize out excessive name binding?

85 Views Asked by At

Can the python compiler optimize away unnecssary name binding ? For example, can a function defined as:

def add_one(x):
    a = x
    b = a
    c = b
    d = c
    e = d
    f = e
    g = f
    return g + 1

be optimized to just

def add_one(x):
    return x + 1
1

There are 1 best solutions below

0
On BEST ANSWER

No, Python can't optimise this case, because Python is a highly dynamic language, names can have meaning at runtime that an optimiser can't predict or account for. Python's inspection features let you retrieve those names at runtime, for example.

While that may seem contrived in your constructed and unlikely scenario, in other, more complex cases assigning an alias to a name that is then used introspected on or otherwise accessed in a call out to another function is not unheard of. For example, the zope.exceptions library looks for __traceback_info__ locals along the stack in case of a traceback. You would not want the compiler to have optimised away those otherwise 'useless' assignments.

There are many more such scenarios that make Python code optimisation much more complex than most developers appreciate.