Question

I am using pdb to debug a program. I successively hit 'c' to run through the code and at each step pdb shows me which line is executed.

Let's say we have this code:

def foo(bar):
   print(bar)

foo('hey')

First, line 4 calls function foo. Then pdb shows me the line

def foo(bar)

is executed.

Why? Is not that line just a kind of label? What happens before "print(bar)" is executed? (that comes with another 's' hit)

EDIT: I experimented that something done is to actually check the definition. In fact, in the case foo were a generator (that cannot be called in such a way) python still gets there and then decides to treat it as a generator (or a function depending the case..).

Was it helpful?

Solution

def is not a declaration in Python, it's an executable statement. At runtime it retrieves the code object compiled for the function, wraps that in a dynamically created function object, and binds the result to the name following the def. For example, consider this useless code:

import dis
def f():
    def g():
        return 1
dis.dis(f)

Here's part of the output (Python 2.7.5 here):

0 LOAD_CONST               1 (<code object g at 02852338, file ...>)
3 MAKE_FUNCTION            0
6 STORE_FAST               0 (g)

All this is usually an invisible detail, but you can play some obscure tricks with it ;-) For example, think about what this code does:

fs = []
for i in range(3):
    def f(arg=i**3):
        return arg
    fs.append(f)
print [f() for f in fs]

Here's the output:

[0, 1, 8]

That's because the executable def creates three distinct function objects, one for each time through the loop. Great fun :-)

OTHER TIPS

What happens before "print(bar)" is executed?

This is just an educated guess: I suppose the current IP is pushed onto the stack and then the parameters. Then a new stack frame is created, the parameters are popped from stack and added as locals to the current scope. Something along this line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top