preface

Recently I had a friend who just graduated from a training institution. The overall technical learning is still very good. I was also successfully interviewed by an Internet company. However, I did not expect to go to work on the first day of a small overturned car. If you’re here, you might have a question, right? Is the technology substandard? NO NO NO. Is it a BUG that has not been solved? Also is not. It crashed because it wrote code that made it look amateurish to older people in the company. In our jargon, the code is noncanonical.

Code specification this thing, usually feel nothing when learning. There are a lot of students didn’t pay much attention. But when we get to the company, we find that code specification is very important.

Because the first one, it shows you as a real development engineer skills, code are not standard, you said you are good skills, it is not true!

Second, in a company, it’s usually team development, and when you do team development, it’s inevitable that your code colleagues will read it. At this point, the code is not standard and you can imagine how embarrassing that can be. It’s like a brilliant student who writes like a first grader.

Third, every company has its own set of development standards. For example, Tencent has Tencent standards, and Ali has Ali standards. A person who does not pay attention to code specifications will suffer greatly when he or she enters the company. So having said so much, it is these small problems that lead to big problems!

So what is a code specification? A code specification is a code that is written in a common way or style. Note that it is not mandatory (that is, there is no error if you do not write according to the specification), but it is a must in “Programmer self-cultivation”.

Today’s focus will be on the Python coding Style Guide, PEP8

PEP8 introduction

PEP 8, which stands for Style Guide for Python Code, covers three broad areas

  • Naming conventions
  • Annotation document
  • Code layout

Naming conventions

Naming conventions are something we’ve been emphasizing, and that’s actually a very extensible topic, where we need to understand the main command rules and the common naming of different elements in Python.

  • Small Hump nomenclature: Consists of one or more LUs. Each LUS can be called an identifier. Each identifier starts with a lowercase letter and the rest with a uppercase letter, for example, firstName

  • “Big hump nomenclature” : Similar to small hump nomenclature, the difference is that the first letter is capitalized. For example: FirstName

  • Underscore naming: Similar to camel name naming, except that all identifiers are lowercase and are connected by underscores (_), for example, first_name

In addition, there are other naming conventions, such as uppercase FIRSTNAME, uppercase combined with the underscore FIRST_NAME, lowercase FIRSTNAME, etc. There are also prefix or suffix underscores, double underscores, and so on in Python.

Common Python naming conventions

For variables and constants:
  • Variable names can be lowercase or underlined;
  • Constants should be written in all uppercase letters, separated by underscores when necessary, and note that there is no concept of const in Python as in other languages. Constants are simply conventions (they are usually placed at the top of code, or in a separate module, or in a specific configuration file).
  • For container variables, the plural noun is often used. For mapping class variables, the form key_value is often used, where key and value are the actual meanings of the key and value. For example: information_value = {“name”:”lili”,”age”:20}
  • For variables or constants that represent booleans (but are not limited to them), it is common to use has and is as prefixes.
For classes (and exceptions) :
  • Class names should use large humps (not including some of Python’s built-in classes, such as int and list), classes and attributes often take nouns, and methods often take verbs or include verbs.
  • Base classes are prefixed with Base and Abstract classes are prefixed with Abstract.
  • Exception names should use the big camel name, and when the exception indicates an Error, add the Error suffix (not all exceptions represent code execution errors, such as KeyboardInterrupt, SystemExit).
For functions and methods:
  • Function and method names should be lowercase, and can also be named with underscores (although we can still see camel names for methods and functions in code, even in Python’s standard library, such as in the threading module, Because this code tends to predate the PEP 8 specification and is reserved for backward compatibility, but often these modules provide lower-case and underlining methods for the same functionality, we should use these new methods whenever possible).
  • The first argument to the instance method should be self, and the first argument to the class method should be CLS (class cannot be used as a keyword and is often replaced by CLS or klass).
For modules and packages:
  • Modules names should be lowercase whenever possible, and underlined if necessary (except for “init” modules)
  • The names of packages should be lowercase and preferably not underlined.
Special format:
  • Single-underscore prefixes, such as _name, are often called “pseudo-private attributes” (also used for private methods, classes, etc.). This naming is a convention in Python for private attributes (note also that from… When importing *, objects of this form are not imported, and such pseudo-private variables are usually obtained or assigned by special methods.) Private attributes usually have no direct external functions, and are often used to record internal state or to provide some public functions in methods.
  • Single-underscore suffixes, such as name_, are often used to avoid collisions with Python keywords;
  • Double underscore prefixes, such as __name, are used for base classes to avoid naming conflicts with subclasses, and Python uses conversion rules to convert them to something like _Class__name, This approach is often called name mangling or name decoration (it is commonly used for multiple inheritance and should be avoided for naming private attributes);
>>> class MyClass:

. __name = 1

.

>>> MyClass.__name  No direct access

Traceback (most recent call last):

  File "<input>", line 1, in <module>

AttributeError: type object 'MyClass' has no attribute '__name'

>>> MyClass._MyClass__name

1

Copy the code
  • Double underscores, such as __name__, are common Python dunder names we mentioned earlier, and should not be customized.

Written comments

Comments are important for reading, extending, and maintaining code. There are three common types of Comments in Python: Block Comments, Inline Comments, and Documentation Strings.

Block Comments
  • Block comments are common within code and usually consist of one or more paragraphs separated by an empty line starting with #. Each paragraph consists of a complete sentence, starting with # and a space on each line. In addition, block comments should be indented at the same level as the commented code to help distinguish the relationship between comments and code. Block comments are shown in the following code:
@classmethod

def fromkeys(cls, iterable, v=None):

    # There is no equivalent method for counters because the semantics

    # would be ambiguous in cases such as Counter.fromkeys('aaabbc', v=2).

    # Initializing counters to zero values isn't necessary because zero

    # is already the default value for counter lookups. Initializing

    # to one is easily accomplished with Counter(set(iterable)). For

    # more exotic cases, create a dictionary first using a dictionary

    # comprehension or dict.fromkeys().

    raise NotImplementedError(

        'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')

Copy the code
Inline Comments
  • An inline comment is a relatively simple comment that is on the same line as an expression or statement, usually separated by two Spaces. The comment section should start with # and a space.
one_list = []  Create a list



Copy the code
Documentation Strings
  • In Python, the most important form of comment is the docstring. It is mainly used in two ways:
    • Used to describe modules, classes, functions, methods, etc.
    • You can work with assistive tools to automate code documentation generation
  • Of course, it may be hard to appreciate the importance of docstrings now, but the word “open source” reminds us that the quality of an open source document depends on its readability, and readability often comes with extensive documentation.
def function_name():

    """docstrings"""

    pass

Copy the code

Code layout

Indent and space

Python syntactically uses indentation to determine the beginning and end of a block of code. For each level of indentation, there should be four Spaces. Of course, in Pycharm we can set the TAB key to indent.

That’s important to note that the indentation itself is mandatory, but the number of Spaces is actually not limited by the syntax. Just indent the same space in the same code.

Of course, we usually use four Spaces.

# 4 Spaces for indentation

def function_name():

    """docstrings"""

    pass





The # 8 Spaces indicate indentation

def function_name_two():

        """docstrings"""

        pass

Copy the code
Empty lines between code

Functions and classes should be separated by two empty lines, and methods inside a class should be separated by one empty line. Blocks of code for different functions in a function or method can be separated by a blank line.

Observe the following code null line rule:

class MyClass(object):

    def method_one(self):

        pass

    

    def method_two(self):

        pass





def function_name():

    """docstrings"""

    pass





def function_name_two():

    """docstrings"""

    pass

Copy the code

OK, code specification is very important to the self-cultivation and professionalism of our programmers. Students must pay attention to every detail. Only in this way can you make yourself to a higher level. https://www.python.org/dev/peps/pep-0008/ for more content you can refer to the document

Finally, I wish you “happy New Year 2021, happy family and good health”.