One Python 2.1 idea

Tim Peters tim.one at home.com
Tue Dec 26 16:26:47 EST 2000


[Russell Turpin]
> ...
> First, I hope Alex Martelli does look at how list
> comprehension is implemented. Even though I am the one
> who has argued that the language features of Python are
> quite mature, I think list comprehension is just the
> right kind of language enhancement, raising the level
> of abstraction in a way that extends seamlessly the
> existing notation.

Same here!  listcomps were a fine addition.

> Second, a question. Consider the invocation of a method,
> such as:
>
>     x.foo()
>
> Does this really cause the lookup of the string "foo"
> in x's namespace dictionary? The first time? Every time?
> Is this also the case when data members are accessed?

First and every time, but that was covered in other msgs.

It's not quite as simple as that, though:  Python interns strings in source
code that "look like" they might be attribute names.  As a result, "foo" is
stored uniquely, and in most cases the lookup of "foo" in the class dict
will succeed via pointer equality:  in most cases no string comparison will
actually be done at runtime, nor will runtime code recompute the hash code
for "foo" (the hash code is cached in the interned string object).  This is
true (no string compare) even if you do

    getattr(x, "foo")

It's *not* true, though, if you do

    getattr(x, "f" + "oo")

Strings synthesized (computed) at runtime are not interned by magic, so the
lookup code ends up dealing with a distinct copy of "foo" and needs to do a
string compare to determine equality.  OTOH,

    getattr(x, intern("f" + "oo"))

again succeeds via cheap pointer equality (which is no real gain, since the
string compare is hiding in the intern() now -- but is a real gain if you
reuse the explicitly interned string in more lookups).

Of course the "cheap pointer equality" doesn't get hit until we're several
layers deep in C function calls, so it's not like this is zippy:  it's just
quicker than you expect at first -- and the time isn't being spent where you
first guess it's being spent.

the-implementation-is-cleverer-than-the-programmer-model-ly
    y'rs  - tim





More information about the Python-list mailing list