accessflyai.clubCreate your AI project with one click.
The author | smiling tiger
Source code | bay
I have been writing Python for 4 or 5 years, and I have always maintained the quality of my code with my own obsessiveness. I have never read a similar book except Google’s Python code specification. I came across such a book by chance and felt good after reading it, so I made a simple note. Want to learn similar knowledge of friends, and too lazy to read a complete book, you can refer to.
An introduction to 1:
1. Understand the Pythonic concept — see Zen of Python in Python
Tip 2: Write Pythonic code
Avoid non-standard code, such as case-sensitive variables, confusing variable names, and fear of excessively long variable names. Sometimes long variable names make code more readable.
In-depth knowledge of Python, such as language features, library features, such as the evolution of Python, etc. Dig deep into one or two of Pythonic’s recognized libraries, such as Flask, etc.
Tip 3: Understand the differences between Python and C, such as indentation and {}, single quotes and double quotes, ternary operators? , switch-case statements, etc.
Tip 4: Add comments to your code as appropriate
Tip 5: Add empty lines to make the layout more reasonable
Tip 6: Four principles for writing functions
Function design should be as short as possible, the nesting level should not be too deep
Function declarations should be reasonable, simple, and easy to use
Function parameter design should consider backward compatibility
A function does only one thing. Try to keep the granularity of the function consistent
Tip 7: Keep constants in one file and use all uppercase letters
2: Programming idioms
Tip 8: Use assert statements to find problems, but be aware that asserting assert affects efficiency
Recommendation 9: Do not use temporary variables when exchanging values. Instead, use a, b = b, A
Recommendation 10: Take advantage of Lazy evaluation to avoid unnecessary calculations
Recommendation 11: Understand the pitfalls of alternative implementations of enumerations (they have been added to recent versions of Python)
Tip 12: It is not recommended to use type for type checking, because sometimes type results are not always reliable. If required, isinstance is recommended instead
Tip 13: Try converting variables to floating point before doing division (forget Python3)
Tip # 14: Beware of security vulnerabilities in the eval() function, somewhat similar to SQL injection
Tip 15: Use enumerate() to obtain both the index and the value of a sequence iteration
Tip 16: Distinguish between == and is, especially when comparing immutable type variables such as strings
Recommendation 17: Use Unicode whenever possible. Coding in Python2 is a headache, but Python3 is not a big concern
Recommendation 18: Build a reasonable package hierarchy to manage modules
3: Basic usage
Tip # 19: Use sparingly from… Import statement to prevent contamination of the namespace
Tip 20: Import modules with absolute import preferred (relative import has been removed from Python3)
Recommendation 21: I +=1 does not equal ++ I. In Python, the plus sign before ++ I only indicates positive, not operation
Tip 22: Get used to using with to automatically close resources, especially in file reads and writes
Tip 23: Use the else clause to simplify loops (exception handling)
Recommendation 24: Follow some basic exception handling principles
Pay attention to the granularity of exceptions and try blocks with as little code as possible
Beware of using separate except statements, or except Exception statements, and instead locate specific exceptions
Pay attention to the order in which exceptions are caught and handle them at the appropriate level
Use more friendly exception information and follow the specification of exception parameters
Tip 25: Avoid pitfalls that can occur in finally
Tip 26: Drill down on None and determine if an object is empty. The following data is judged to be null in Python:
Recommendation 27: Join strings should use the join function in preference to the + operation
Recommendation 28: Use the. Format function instead of % when formatting strings
Recommendation 29: Treat mutable and immutable objects differently, especially as function arguments
Recommendation 30: [], {} and () : consistent container initialization forms. Using list parsing can make your code cleaner and more efficient
Recommendation 31: Functions pass arguments, neither values nor references, but objects or references to objects
Tip 32: Be aware of potential problems with default arguments, especially if they are mutable objects
Recommendation 33: Be careful with variable length arguments *args and **kargs in functions
This is too flexible and makes the function signature less legible and less readable
If the function definition is simplified with variable-length arguments because it has too many arguments, the function can generally be refactored
Recommendation 34: Understand the difference between STR () and repr()
The goals are different: STR is customer-oriented, for readability, and returns a string that is user-friendly and readable; Repr, on the other hand, is for the Python interpreter, or Python developer, for accuracy, and the return value represents the internal definition of the Python interpreter
By entering variables directly in the interpreter, the repr function is called by default, while print(var) calls STR by default
The return value of the repr function can normally be used to restore the object using the eval function
Both call the object’s built-in functions __str__() and __repr__(), respectively.
Tip 35: Distinguish between staticMethod and classMethod
4: library
Recommendation 36: Master the basic usage of strings
Recommendation 37: Select the sort() and sorted() functions as needed
Sort () is where the list is sorted, so immutable types such as tuples cannot be sorted.
Sorted () sorts arbitrary iterable types without changing the original variable itself.
Recommendation 38: Use the copy module deep copy object to distinguish between shallow and deep copies.
Tip 39: Count statistics using Counter, which is a subclass of the dictionary class in the Collections module
Recommendation 40: Go deep with ConfigParser
Recommendation 41: Use the argparse module to handle command line arguments
Recommendation 42: Use pandas to process large CSV files
Python itself provides a CSV file processing module and reader, writer, and other functions.
Pandas provides partitioning and merging for large amounts of data and is convenient for manipulating two-dimensional data.
Recommendation 43: Use ElementTree to parse XML
Tip 44: Understand the pros and cons of module pickling
Advantages: Simple interface, universal platform, wide range of supported data types, strong scalability
Disadvantages: atomicity of data operation is not guaranteed, security problems exist, incompatibility between different languages
Recommendation 45: Alternative JSON modules for serialization: load and dump operations
Recommendation 46: Use traceback to obtain stack information
Recommendation 47: Use logging to record log information
Tip 48: Write multithreaded programs using the threading module
Recommendation 49: Use the Queue module to make multithreaded programming safer
5: Design patterns
Recommendation 50: Implement the singleton pattern with modules
Tip 51: Use mixin patterns to make your application more flexible
Recommendation 52: Use publish-subscribe for loose coupling
Tip 53: Beautify your code with state patterns
6: Internal mechanisms
Tip 54: Understand build-in objects
Recommendation 55: __init__() is not a constructor, understand the difference between __new__() and it
Recommendation 56: Understand the look-up mechanism for variables, called scope
Local scope
Global scope
Nested scopes
Built-in scope
Recommendation 57: Why do I need the self parameter
Recommendation 58: Understand MRO (method parsing order) and multiple inheritance
Tip 59: Understand the descriptor mechanism
Tip 60: Distinguish between __getattr__() and __getAttribute__ () methods
Recommendation 61: Use a more secure property
Recommendation 62: Master metaclass
Recommendation 63: Be familiar with the Python object protocol
Recommendation 64: Use operator overloading for infix syntax
Tip 65: Be familiar with Python’s iterator protocol
Tip 66: Be familiar with Python generators
Recommendation 67: Generator-based coroutines and greenlets, understand the differences between coroutines, multithreading, and multiprocesses
Recommendation 68: Understand the limitations of the GIL
Recommendation 69: Object management and garbage collection
7: Use tools to assist project development
Recommendation 70: Install third-party packages from PyPI
Recommendation 71: Install and manage packages using PIP and technique
Recommendation 72: Do paster to create a package
Recommendation 73: Understand the concept of unit testing
Recommendation 74: Write unit tests for packages
Recommendation 75: Use test-driven development (TDD) to improve your code’s testability
Tip 76: Use Pylint to check code style
Code style review
Code error checking
Find duplicates and unreasonable code for easy refactoring
Highly configurable and customizable
Supports integration of various ides and editors
Ability to generate UML diagrams based on Python code
Can be combined with continuous integration tools such as Jenkins to support automatic code review
Recommendation 77: Conduct effective code reviews
Recommendation 78: Publish packages to PyPI
8: Performance analysis and optimization
Recommendation 79: Understand the basic principles of code optimization
Recommendation 80: Use performance tuning tools
Recommendation 81: Use cProfile to locate performance bottlenecks
Recommendation 82: Use Memory_profiler and objGraph to profile memory usage
Recommendation 83: Try to reduce algorithm complexity
Recommendation 84: Master the basics of loop optimization
Reduce computation inside the loop
Change an explicit loop to an implicit loop, which of course compromises code readability
Try to reference local variables in the loop
Focus on inner nested loops
Tip 85: Use generators for efficiency
Recommendation 86: Optimize performance with different data structures
Recommendation 87: Take advantage of set
Recommendation 88: Use the Multiprocessing module to overcome GIL defects
Recommendation 89: Use thread pools for efficiency
Recommendation 90: Use C/C++ module extensions to improve performance
Recommendation 91: Write extension modules using Cythonb
Visit Flyai. club to create your AI project with one click.
End