Skip to content

Instantly share code, notes, and snippets.

@svvitale
Last active May 1, 2020 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svvitale/c558b42f559d0bf8b33b1106183da9c8 to your computer and use it in GitHub Desktop.
Save svvitale/c558b42f559d0bf8b33b1106183da9c8 to your computer and use it in GitHub Desktop.
Vitale's Python Style Guide

Operator Overrides

I absolutely love using operator overrides in low-level objects because it can make the caller's use case WAY more intuitive. There are certainly some pitfalls though.

  1. If you're overriding __getitem__ and __setitem__ to make an object more dictionary-like, make sure to also override __iter__ OR __contains__ since they're called to handle membership tests like in and not in. (ref: https://docs.python.org/3/reference/expressions.html#membership-test-operations)

Enums

Enums can be a little tedious in Python, but there are a few things I try to do to streamline usage:

  1. Never build lists or structures that contain the Enum entry names or values, unless some level of serialization is being done. Always use Enum instances themselves.
  2. Only use .value or .name at the very lowest level of your code, and only if necessary. Most comparisons, set operations, and looping can be done with the Enum instances directly.

Exception Handling

For long running tasks or functions in Python, it's sometimes helpful to use a while True loop in concert with a generalized except Exception handler. This will generally work fine, but remember to exclude exceptions that truly should be raised, such as KeyboardInterrupt and CancelledError (in the case of code run within an async task/co-routine).

Before:

while True:
    try:
        # Do some stuff
        ...

    except Exception as ex:
        # Bad stuff happened, handle it however you need to.
        ...

After:

while True:
    try:
        # Do some stuff
        ...

    except asyncio.CancelledError:
        # This task has been cancelled.
        raise

    except Exception as ex:
        # Bad stuff happened, handle it however you need to.
        ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment