Style Guide For Python Code

Start from the beginning
                                        

      mixedCase is allowed only in contexts where that's already the

      prevailing style (e.g. threading.py), to retain backwards compatibility.

    Function and method arguments

      Always use 'self' for the first argument to instance methods.

      Always use 'cls' for the first argument to class methods.

      If a function argument's name clashes with a reserved keyword, it is

      generally better to append a single trailing underscore rather than use

      an abbreviation or spelling corruption.  Thus "print_" is better than

      "prnt".  (Perhaps better is to avoid such clashes by using a synonym.)

    Method Names and Instance Variables

      Use the function naming rules: lowercase with words separated by

      underscores as necessary to improve readability.

      Use one leading underscore only for non-public methods and instance

      variables.

      To avoid name clashes with subclasses, use two leading underscores to

      invoke Python's name mangling rules.

      Python mangles these names with the class name: if class Foo has an

      attribute named __a, it cannot be accessed by Foo.__a.  (An insistent

      user could still gain access by calling Foo._Foo__a.)  Generally, double

      leading underscores should be used only to avoid name conflicts with

      attributes in classes designed to be subclassed.

      Note: there is some controversy about the use of __names (see below).

    Constants

       Constants are usually defined on a module level and written in all

       capital letters with underscores separating words.  Examples include

       MAX_OVERFLOW and TOTAL.

    Designing for inheritance

      Always decide whether a class's methods and instance variables

      (collectively: "attributes") should be public or non-public.  If in

      doubt, choose non-public; it's easier to make it public later than to

      make a public attribute non-public.

      Public attributes are those that you expect unrelated clients of your

      class to use, with your commitment to avoid backward incompatible

      changes.  Non-public attributes are those that are not intended to be

      used by third parties; you make no guarantees that non-public attributes

      won't change or even be removed.

      We don't use the term "private" here, since no attribute is really

      private in Python (without a generally unnecessary amount of work).

Docstring ConventionsWhere stories live. Discover now