Search code examples
pythonoptimizationunused-variables

Is Python allowed to optimize a function definition to eliminate unused code?


If I defined a function like this:

def ccid_year(seq):
  year, prefix, index, suffix = seq
  return year

Is Python allowed to optimize it to be effectively:

def ccid_year(seq):
  return seq[0]

I'd prefer to write the first function because it documents the format of the data being passed in but would hope that Python would generate code that is effectively as efficient as the second definition.


Solution

  • The two functions are not equivalent:

    def ccid_year_1(seq):
      year, prefix, index, suffix = seq
      return year
    
    def ccid_year_2(seq):
      return seq[0]
    
    arg = {1:'a', 2:'b', 0:'c', 3:'d'}
    print ccid_year_1(arg)
    print ccid_year_2(arg)
    

    The first call prints 0 and the second prints c.