Python is well-known for its structure, but also known for its naming conventions, chaotic and irregular naming especially for developers to bring understanding of the misunderstanding.
In particular, like Python, ruby Dynamic language, the naming of rules is especially important due to the possibility of adding or subtracting methods or attributes at any time during the run time. The Ruby language itself defines the grammatical rules more arbitrarily, but there are no lack of one by one corresponding to the implied rules, make people at a glance. Its naming rules even penetrate into the language itself in the specification of the naming rules that Python appears to have no distance. It is necessary to develop a good coding naming specification gradually. This article collects some code style, naming specification from each major site article. Easy to learn reference. Code style:
There is no time to translate at last, there is time to come again. reference:http://www.python.org/dev/peps/pep-0008/#naming-conventions Programming recommendations
-
Code should is written in a-the-does not disadvantage-other implementations of Python (PyPy, Jython, Ironpytho N, Cython, Psyco, and such).
For example, does not rely on CPython ' s efficient implementation of in-place-string concatenation for statements in the F orm 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 would ensure that concatenation occurs in linear time across various implementations.
Comparisons to singletons-like None should always be do with is or was not, never the equality operator S.
Also, beware of writing if x when you really mean if x are not None--e.g. when testing whether a Variab Le or argument that defaults to None is set to some and other value. The other value might has a type (such as a container) that could is false in a Boolean context!
When implementing ordering operations with rich comparisons, it's 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 C Omparison methods.
PEP 207 indicates that reflexivity rules is 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 is guaranteed to use the < operator and the Max () function uses the ; operator. However, it is the best-implement all six operations-confusion doesn ' t arise in other contexts.
-
Use class-based exceptions.
String Exceptions in new code was forbidden, because this language feature was being removed in Python 2.6.
Modules or packages should define their own domain-specific base exception class, which should is subclassed from the B Uilt-in Exception class. Always include a class docstring. e.g.:
class Messageerror (Exception): "" "Base class for errors in the e-mail package." "
Class Naming conventions apply here, although you should add the suffix "Error" to your exception classes, if the EXCEP tion is an error. Non-error exceptions need no special suffix.
When raising a exception, use raise ValueError (' message ') instead of the older form raise ValueError, ' Messa GE '.
The Paren-using form is preferred because when the exception arguments be long or include string formatting, you don ' t NE Ed to use line continuation characters thanks to the containing parentheses. The older form would be removed in Python 3.
When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.
For example, use:
Try: import platform_specific_moduleexcept importerror: platform_specific_module = None
A bare except: clause'll catch Systemexit and keyboardinterrupt exceptions, making it harder to interrupt a pro Gram with control-c, and can disguise other problems. If you want to catch all exceptions this signal program errors, use except Exception: (bare except is equivalent To except baseexception:).
A good rule of thumb is the to limit use of the bare ' except ' clauses to both cases:
- If the exception handler would be is printing out or logging the traceback; At least the user would be aware, that's the error has occurred.
- If the code needs to does some cleanup work, and then lets the exception propagate upwards with raise. try...finally can be a better-handle this case.
-
Additionally, for any try/except clauses, limit the try clause to the absolute minimum amount of Code necessary. Again, this avoids masking bugs.
Yes:
try:value = collection[key]except keyerror:return key_not_found (key) Else:return Handle_value (value)
No:
Try: # Too broad! Return Handle_value (Collection[key]) except Keyerror: # would also catch Keyerror raised by Handle_value () return Key_ Not_found (key)
Context managers should be invoked through separate functions or methods whenever they doing something other than acquire and Release resources. For example:
Yes:
With Conn.begin_transaction (): do_stuff_in_transaction (conn)
No:
With Conn: do_stuff_in_transaction (conn)
The latter example doesn ' t provide any information to indicate that the __enter__ and __exit__ methods is doing something Other than closing the connection after a transaction. Being Explicit is important in the this case.
Use string methods instead of the string module.
String methods is always much faster and share the same API with Unicode strings. Override This rule if backward compatibility with Pythons older than 2.0 is required.
Use ". StartsWith () and ". EndsWith () instead of string slicing to check for prefixes or suffixes.
StartsWith () and EndsWith () is cleaner and less error prone. For example:
Yes:if foo.startswith (' Bar '): No: if foo[:3] = = ' Bar ':
The exception is if your code must work with Python 1.5.2 (but let ' s hope not!).
Object type comparisons should always use Isinstance () instead of comparing types directly.
Yes:if isinstance (obj, int): No: if Type (obj) is type (1):
When checking if an object was a string, keep in mind that it might be a Unicode string too! In Python 2.3, str and Unicode has a common base class, basestring, so can do:
If Isinstance (obj, basestring):
For sequences, (strings, lists, tuples), use the fact, empty sequences is false.
Yes:if not seq: if Seq:No:if len (seq) if not len (seq)
Don ' t write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) would trim them.
Don ' t compare Boolean values to True or False using = =.
Yes: If greeting:no: if greeting = = True:Worse:if Greeting is True:
The Python standard library would not use function annotations as, would result in a premature commitment to a particul AR annotation style. Instead, the annotations is left for users to discover and experiment with useful annotation styles.
Early Core Developer attempts to use function annotations revealed inconsistent, Ad-hoc annotation styles. For example:
- [STR] was ambiguous as-whether it represented a list of strings or a value that could be either str o R None.
- The notation open (file: (str,bytes)) is used for a value, could be either bytes or str rath Er than a 2-tuple containing a str value followed by abytes value.
- The annotation seek (Whence:int) exhibited a mix of over-specification and under-specification: int is t OO restrictive (anything with __index__ would being allowed) and it is not restrictive enough (only the values 0, 1, and 2 are allowed). Likewise, the annotation write (b:bytes) was also too restrictive (anything supporting the buffer protocol would be allowed).
- Annotations such as read1 (N:int=none) were self-contradictory since None is not a int. Annotations such as Source_path (self, FULLNAME:STR)-objectwere confusing about what the return type should Be.
- In addition to the above, annotations were inconsistent in the use of concrete types versus abstract types: int v Ersus Integral and Set/frozenset versus Mutableset/set.
- Some annotations in the abstract base classes were incorrect specifications. For example, Set-to-set operations require and other to being another instance of set rather than just an I Terable.
- A further issue is that annotations become part of the specification but weren ' t being tested.
- In most cases, the docstrings already included the type specifications and do so with greater clarity than the function a Nnotations. In the remaining cases, the docstrings were improved once the annotations were removed.
- The observed function annotations were too ad-hoc and inconsistent to work with a coherent system of automatic type Checki ng or argument validation. Leaving these annotations in the code would has made it more difficult to make changes later so that automated utilities could be supported.