How to explain exactly what "def" does?

John Roth johnroth at ameritech.net
Mon Feb 3 19:53:19 EST 2003


"Roy Smith" <roy at panix.com> wrote in message
news:b1mhoj$fha$1 at panix2.panix.com...
> While explaining the basics of Python to somebody who's brain had been
> corrupted by Perl as a first language, I came upon an interesting
> wrinkle.  We were talking about containers and names and dynamic
> vs. static typing when I gave the following demo:
>
> ----------------------------------
> >>> def foo():
> ...     print "hello"
> ...
> >>> foo()
> hello
>
> # So far, so good.  I've defined a function and called it.
> # Nothing mysterious going on yet.
>
> >>> z = foo
> >>> z()
> hello
>
> # This is the gist of what I was trying to demonstate, that
> # names can be bound to anything, and the value of something
> # can be a function just as easily as it can be an integer.
>
> >>> foo.__name__
> 'foo'
>
> # Still no problem, a function knows it's name.
>
> >>> z.__name__
> 'foo'
>
> # Huh???
> ----------------------------------
>
> I know why z.__name__ printed 'foo', but I'm not quite sure I know how
> to explain it (at least not without delving into horrible stuff like
> lambdas which are sure to just confuse my audience).
>
> So, what exactly does "def foo" do?  It seems that it does two things.
> First, it defines a function, and gives that function's __name__
> attribute the value "foo".  At the same time, it also defines a name
> "foo" in the current namespace, and binds it to the function that was
> just defined.  Is that a good (i.e. correct) way to explain it?

That's exactly correct if you don't want to know the ugly mechanics
behind it. The only additional thing to emphasize is that the "foo"
that's
printed has nothing to do with the variable it's bound to. If you rebind
the function to another variable, like this:

>>>bar = foo
>>>bar.__name__
'foo'

is what you should still see.

When the def statement is compiled, the compiler creates a code
object. It might also create a function object, but I don't think so.
I think that's created when def statement is actually executed and the
function object is bound to its name.

John Roth






More information about the Python-list mailing list