[Python-Dev] Draft Guide for code migration and modernation
Skip Montanaro
skip@pobox.com
Mon, 3 Jun 2002 14:05:33 -0500
Raymond> Pattern: if d.has_key(k): --> if k in d:
Raymond> Idea: For testing dictionary membership, use the 'in' keyword
Raymond> instead of the 'has_key()' method.
Raymond> Version: 2.2 or greater
Raymond> Benefits: The result is shorter and more readable. The style
Raymond> becomes consistent with tests for membership in lists. The
Raymond> result is slightly faster because has_key requires an attribute
Raymond> search.
Also faster (I think) because it avoids executing the expensive
CALL_FUNCTION opcode. (Probably applies to the d.keys() part of second
pattern as well.)
Raymond> Pattern: if v == None --> if v is None:
Raymond> Idea: Since there is only one None object, it can be tested
Raymond> with identity.
Raymond> Version: Any
Raymond> Benefits: Identity tests are slightly faster than equality
Raymond> tests. Also, some object types may overload comparison to be
Raymond> much slower (or even break).
Raymond> Locating: grep '== None' or grep '!= None'
Also:
if v: --> if v is None
where appropriate (often when testing function arguments that default to
None). This may change semantics though and has to be undertaken with some
care.
Skip