How to explain exactly what "def" does?

Roy Smith roy at panix.com
Mon Feb 3 15:00:19 EST 2003


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?  Is
there a better way that might make more sense to a non computer
scientist?

Some time later, she came back and wanted to know why

for x in [1, 2, 3, 4, 5, 6]:
    print x if x < 3:

didn't work :-(  See what I was talking about when I said her brain
had been corrupted by Perl?




More information about the Python-list mailing list