Python from Wise Guy's Viewpoint

Peter Hansen peter at engcorp.com
Sun Oct 19 10:20:11 EDT 2003


(I'm replying only because I made the mistake of replying to a
triply-crossposted thread which was, in light of that, obviously
troll-bait.  I don't plan to continue the thread except to respond
to Frode's questions.  Apologies for c.l.p readers.)

Frode Vatvedt Fjeld wrote:
> 
> Peter Hansen <peter at engcorp.com> writes:
> 
> > Both are correct, in essence.  (And depending on how one interprets
> > your second point, which is quite ambiguous.)
> 
> Frode Vatvedt Fjeld wrote:
> 
> >>   1. Function names (strings) are resolved (looked up in the
> >>      namespace) each time a function is called.
> 
> But this implies a rather enormous overhead in calling a function,
> doesn't it?

"Enormous" is of course relative.  Yes, the overhead is more than in,
say C, but I think it's obvious (since people program useful software
using Python) that the overhead is not unacceptably high? 

As John Thingstad wrote in his reply, there is a dictionary lookup
involved and dictionaries are extremely fast (yes, yet another relative
term... imagine that!) in Python so that part of the overhead is
relatively unimportant.  There is actually other overhead which is
involved (e.g. setting up the stack frame which is, I believe, much larger
than the trivial dictionary lookup).

Note also that if you have a reference to the original function is,
say, a local variable, removing the original doesn't really remove it,
but merely makes it unavailable by the original name.  The local variable
can still be used to call it.

> >>   2. You can't really undefine a function such that existing calls to
> >>      the function will be affected.
> 
> What I meant was that if you do the following, in sequence:
> 
>   a. Define function foo.
>   b. Define function bar, that calls function foo.
>   c. Undefine function foo
> 
> Now, if you call function bar, will you get a "undefined function"
> exception? But if point 1. really is true, I'd expect you get a
> "undefined name" execption or somesuch.

See below.

Python 2.3.1 (#47, Sep 23 2003, 23:47:32) [MSC v.1200 32 bit (Intel)] on win32
>>> def foo():
...   print 'in foo'
...
>>> def bar():
...   foo()
...
>>> bar()
in foo
>>> del foo
>>> bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in bar
NameError: global name 'foo' is not defined

On the other hand, as I said above, one can keep a reference to the original.
If I'd done "baz = foo" just before the "del foo", then I could easily have
done "baz()" and the original method would still have been called.

Python is dynamic.  Almost everything is looked up in dictionaries at 
runtime like this.  That's its nature, and much of its power (as with
the many other such languages).

-Peter




More information about the Python-list mailing list