Version 3 (modified by jdsiiro, 5 years ago) (diff)


Efficiency of Python Idioms

Profiling and improving the performance of any Python code requires some familiarity with the efficiency of key idioms in the Python language. Here we document some common idioms and their relative performance.

Testing Truth

When constructing logical control expressions, how should we check for "truth"?

  • Guidance:
    • prefer "if x:" and "if not x:"
    • avoid "if x == True:" or "if x is True:"
  • Justification: source Download, results Download

Function Signatures

When defining and calling functions, Python allows several flexible formats, including classic positional arguments and keyword arguments. Arguments may provide default values. Variable (unspecified) positional and keyword arguments are allowed.

  • Guidance:
    • prefer explicit positional arguments with default values
    • avoid unspecified keyword arguments (e.g., the "**kwds" idiom)
  • Justification: source Download, results Download