Style Guide For Python Code

Start from the beginning
                                        

        name, you can still get name collisions.

        Note 2: Name mangling can make certain uses, such as debugging and

        __getattr__(), less convenient.  However the name mangling algorithm

        is well documented and easy to perform manually.

        Note 3: Not everyone likes name mangling.  Try to balance the

        need to avoid accidental name clashes with potential use by

        advanced callers.

Programming Recommendations

    - Code should be written in a way that does not disadvantage other

      implementations of Python (PyPy, Jython, IronPython, Pyrex, Psyco,

      and such).

      For example, do not rely on CPython's efficient implementation of

      in-place string concatenation for statements in the form a+=b or a=a+b.

      Those statements run more slowly in Jython.  In performance sensitive

      parts of the library, the ''.join() form should be used instead.  This

      will ensure that concatenation occurs in linear time across various

      implementations.

    - Comparisons to singletons like None should always be done with

      'is' or 'is not', never the equality operators.

      Also, beware of writing "if x" when you really mean "if x is not None"

      -- e.g. when testing whether a variable or argument that defaults to

      None was set to some other value.  The other value might have a type

      (such as a container) that could be false in a boolean context!

    - When implementing ordering operations with rich comparisons, it is best to

      implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__,

      __ge__) rather than relying on other code to only exercise a particular

      comparison.

      To minimize the effort involved, the functools.total_ordering() decorator

      provides a tool to generate missing comparison methods.

      PEP 207 indicates that reflexivity rules *are* assumed by Python.  Thus,

      the interpreter may swap y>x with x<y, y>=x with x<=y, and may swap the

      arguments of x==y and x!=y.  The sort() and min() operations are

      guaranteed to use the < operator and the max() function uses the >

      operator.  However, it is best to implement all six operations so that

      confusion doesn't arise in other contexts.

    - Use class-based exceptions.

      String exceptions in new code are forbidden, because this language

Docstring ConventionsWhere stories live. Discover now