What makes functions special?

Carl Banks pavlovevidence at gmail.com
Sun Jul 10 04:47:08 CEST 2011


On Saturday, July 9, 2011 2:28:58 PM UTC-7, Eric Snow wrote:
> A tracker issue [1] recently got me thinking about what makes
> functions special.  The discussion there was regarding the distinction
> between compile time (generation of .pyc files for modules and
> execution of code blocks), [function] definition time, and [function]
> execution time.  Definition time actually happens during compile time,

Nope.  Compile time and definition time are always distinct.


> but it has its own label to mark the contrast with execution time.  So
> why do functions get this special treatment?

They don't really.


[snip]
> Am I wrong about the optimization expectation?

As best as I can tell, you are asking (in a very opaque way) why the Python compiler even bothers to create code objects, rather than just to create a function object outright, because it doesn't (you think) do that for any other kind of object.

Two answers (one general, one specific):

1. You're looking for a pattern where it doesn't make any sense for there to be one.  The simple truth of the matter is different syntaxes do different things, and there isn't anything more to it.  A lambda expression or def statement does one thing; a different syntax, such as an integer constant, does another thing.  Neither one is treated "specially"; they're just different.

Consider another example: tuple syntax versus list syntax.  Python will often build the tuple at compile time, but it never builds a list at compile time.  Neither one is "special"; it's just that tuple syntax does one thing, list syntax does a different thing.

2. Now that we've dispensed with the idea that Python is treating functions specially, let's answer your specific question.  It's not special, but still, why the code object?

The reason, simply, is that code objects are used for more than just functions.  Code objects are also used in modules, and in eval and exec statements, and there's one for each statement at the command line.  Code objects are also used directly by the interpreter when executing byte code.  A function object is only one of several "interfaces" to a code object.

A minor reason is that code objects are constant (in fact, any object that is built at compile time must be a constant).  However, function objects are mutable.

I hope that helps clear things up.


Carl Banks



More information about the Python-list mailing list