Effective Python 66 - 70

Click here for the first post, which contains the context of this series.

Item #66: Consider contextlib and with statements for reusable try/finally behavior.

  • The with statement allows you to reuse logic from try/finally blocks and reduce visual noise.
  • The contextlib built-in module provides a contextmanager decorator that makes it easy to use your own functions in with statements.
  • The value yielded by context managers is supplied to the as part of the with statement. It is useful for letting your code directly access the cause of a special context.

Item #67: Use datetime instead of time for local clocks.

  • Avoid using the time module for translating between different time zones.
  • Use the datetime built-in module along with the pytz community module to reliably convert between times in different time zones.
  • Always represent time in UTC and do conversions to local time as the very final step before presentation.

Item #68: Make pickle reliable with copyreg.

  • The pickle built-in module is useful only for serializing and deserializing objects between trusted programs.
  • Deserializing previously pickled objects may break if the classes involved have changed over time (e.g., attributes have been added or removed).
  • Use the copyreg built-in module with pickle to ensure backward compatibility for serialized objects.

Item #69: Use decimal when precision is paramount.

  • Python has built-in types and classes in modules that can represent practically every type of numerical value.
  • The Decimal class is ideal for situations that require high precision and control over rounding behavior, such as computations of monetary values.
  • Pass str instances to the Decimal constructor instead of float instances if it's important to compute exact answers and not floating point approximations.

Item #70: Profile before optimizing.

  • It's important to profile Python programs before optimizing because the sources of slowdowns are often obscure.
  • Use the cProfile module instead of the profile module because it provides more accurate profiling information. The Profile object's runcall method provides everything you need to profile a tree of function calls in isolation.
  • The Stats object lets you select and print the subset of profiling information you need to see to understand your program's performance.