Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you write a variable name alone in python?

Recently I became curious about but what happens in line 2 of the following bogus python code:

def my_fun(foo,bar):
    foo
    return foo + bar

The reason I became interested is that I'm trying Light Table and tried to put a watch on "foo." It appeared to cause the python interpreter to hang.

Am I correct in thinking that this line has absolutely no effect and does not cause any sort of error? Can someone explain what the interpreter does exactly here?

like image 865
foobarbecue Avatar asked Jan 21 '14 14:01

foobarbecue


1 Answers

One can look at what is happening with a little help from the built-in dis module:

import dis

def my_fun(foo,bar):
    foo
    return foo + bar

dis.dis(my_fun)

The dis.dis function disassembles functions (yep, it can disassemble itself), methods, and classes.

The output of dis.dis(my_fun) is:

  4           0 LOAD_FAST                0 (foo)
              3 POP_TOP

  5           4 LOAD_FAST                0 (foo)
              7 LOAD_FAST                1 (bar)
             10 BINARY_ADD
             11 RETURN_VALUE

The first two bytecodes are exactly what we need: the foo line.

Here's what these bytecodes do:

  1. The first one pushes a reference to a local variable foo onto the stack (LOAD_FAST)
  2. The second one removes the top of the stack (POP_TOP)

Basically, foo line has no effect. (well, if foo variable is not defined then LOAD_FAST will throw the NameError)

like image 79
Nigel Tufnel Avatar answered Oct 19 '22 22:10

Nigel Tufnel