Using String Methods In Jump Tables
Tim Daneliuk
tundra at tundraware.com
Tue Aug 24 09:06:04 EDT 2010
On 8/23/2010 4:22 PM, Hrvoje Niksic wrote:
> Tim Daneliuk <tundra at tundraware.com> writes:
>
>> You can get away with this because all string objects appear to point to common
>> method objects. That is,: id("a".lower) == id("b".lower)
>
> A side note: your use of `id' has misled you. id(X)==id(Y) is not a
> perfect substitue for the X is Y. :)
>
> "a".lower and "b".lower obviously cannot be the same object, because in
> that case, how could they behave differently when called?
>
>>>> "a".lower()
> 'a'
>>>> "b".lower() # this should also return 'a' if "b".lower is the
> # same object
> 'b'
>
> Yet, id("a".lower) == id("b".lower) evaluates as True.
>
> What happens is, when the expression id("a".lower) == id("b.lower") is
> evaluated, each of the bound method objects created with subexpressions
> "a".lower" and "b".lower is referenced and thrown away as soon as "id"
> is called (i.e. pretty much immediately), so the two never exist at the
> same time. By the time "b".lower needs to be created, "a".lower is
> freshly deceased, and the memory it used to occupy is ready for use, and
> waiting at the top of the freelist.
>
> If CPython happened to use a different allocation/garbage collection
> strategy and failed to reuse the same memory address immediately, your
> code would just (happen to) work.
Thanks for the clarification.
--
------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com
More information about the Python-list
mailing list