Common Python Idioms
Georg Brandl
g.brandl-nospam at gmx.net
Thu Dec 7 08:17:12 EST 2006
Stephen Eilert wrote:
> Hendrik van Rooyen escreveu:
>
>> <skip at pobox.com> wrote:
>>
>> > Peter> Bjoern Schliessmann wrote:
>> > >> Wouldn't be "if k in d.keys()" be the exact replacement?
>> >
>> > Peter> No, 'k in d' is equivalent to 'd.has_key(k)', only with less
>> > Peter> (constant) overhead for the function call. 'k in d.keys()' on the
>> > Peter> other hand creates a list of keys which is then searched linearly
>> > Peter> -- about the worst thing you can do about both speed and memory
>> > Peter> footprint.
>
> I've always used has_key(), thinking it was the only way to do it.
> Given that Python says that "There Should Be Only One Way to Do It", I
> didn't bother searching for alternatives.
>
> Is there a list somewhere listing those not-so-obvious-idioms? I've
> seen some in this thread (like the replacement for .startswith).
>
> I do think that, if it is faster, Python should translate
> "x.has_key(y)" to "y in x".
How and when should it do that?
Georg
More information about the Python-list
mailing list