0

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
RBF06
  • 2,013
  • 2
  • 21
  • 20
  • 3
    I'm not sure whether to interpret this question as "does the CPython bytecode compiler currently do this optimization?" or "if I wrote my own compiler, would the language specification allow me to write this optimization?". The answer might not be the same for both. – Kevin Jan 10 '19 at 15:04

1 Answers1

3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343