Source丨Internet
Coding Principles
Tip 1: Understand the concept of Pythonic—see Zen of Python in Python for details.
Tip 2: Write Pythonic code
(1) Avoid non-standard code, such as using case to differentiate variables, using confusing variable names, or being afraid of long variable names. Sometimes long variable names can make the code more readable.
(2) Deeply learn Python-related knowledge, such as language features, library features, etc., like the evolution of Python. Deeply study one or two industry-recognized Pythonic code libraries, such as Flask.
Tip 3: Understand the differences between Python and C, such as indentation vs. {}, single vs. double quotes, ternary operator ?, Switch-Case statements, etc.
Tip 4: Appropriately add comments in the code.
Tip 5: Add blank lines appropriately to make the code layout more reasonable.
Tip 6: Four principles for writing functions
(1) Function design should be kept short, and nesting levels should not be too deep.
(2) Function declarations should be reasonable, simple, and easy to use.
(3) Function parameter design should consider backward compatibility.
(4) A function should do one thing only, maintaining consistency in function granularity.
Tip 7: Centralize constants in one file, and use all uppercase letters for constant names.
Programming Idioms
Tip 8: Use assert statements to discover problems, but note that assertions can affect efficiency.
Tip 9: When exchanging values, do not use temporary variables; instead, use a, b = b, a
.
Tip 10: Make full use of lazy evaluation to avoid unnecessary calculations.
Tip 11: Understand the drawbacks of implementing replacements with enums (the latest version of Python has added enum features).
Tip 12: Avoid using type for type checking, as sometimes the results of type are not reliable. If needed, use the isinstance function instead.
Tip 13: Try to convert variables to float before division (not a concern after Python 3).
Tip 14: Be cautious of security vulnerabilities with the eval() function, which is somewhat similar to SQL injection.
Tip 15: Use enumerate() to simultaneously get the index and value of the sequence iteration.
Tip 16: Distinguish the use cases of == and is, especially when comparing strings and other immutable types (see comments for details).
Tip 17: Prefer using Unicode. In Python 2, encoding is quite troublesome, but in Python 3, it is not a major concern.
Tip 18: Build a reasonable package hierarchy to manage modules.
Programming Idioms 2
Tip 19: Use from…import statements sparingly to prevent namespace pollution.
Tip 20: Prefer absolute imports to import modules (relative imports have been removed in Python 3).
Tip 21: i += 1
does not equal ++i
; in Python, the plus sign before i simply indicates positive, not an operation.
Tip 22: Habitually use with to automatically close resources, especially when reading and writing files.
Tip 23: Use else clauses to simplify loops (exception handling).
Tip 24: Follow a few basic principles for exception handling (1) Pay attention to the granularity of exceptions, and try to write less code in the try block.
(2) Be cautious when using standalone except statements or except Exception statements; instead, target specific exceptions.
(3) Pay attention to the order of exception capture, handling exceptions at the appropriate level.
(4) Use more user-friendly exception messages, adhering to the specifications for exception parameters.
Tip 25: Avoid potential pitfalls in finally blocks.
Tip 26: Deeply understand None and correctly judge whether an object is empty.
Tip 27: Prefer using the join function for connecting strings rather than the + operator.
Tip 28: When formatting strings, prefer using the format function rather than the % form.
Tip 29: Treat mutable and immutable objects differently, especially when they are function parameters.
Tip 30: Use consistent container initialization forms with [], {}, and (). Using list comprehensions can make the code clearer and more efficient.
Tip 31: Passing parameters to functions is neither passing by value nor by reference, but passing objects or references to objects.
Tip 32: Be cautious of potential issues with default parameters, especially when the default parameter is a mutable object.
Tip 33: Use variable-length parameters args and kwargs sparingly in functions.
(1) This usage is too flexible, making function signatures unclear and reducing readability.
(2) If variable-length parameters are used to simplify function definitions due to excessive parameters, then the function can generally be refactored.
Tip 34: Deeply understand the differences between str() and repr().
(1) The goals of the two are different: str is primarily for users, aiming for readability, returning a user-friendly and readable string; whereas repr is aimed at the Python interpreter or Python developers, aiming for accuracy, returning a value that represents the internal definition of the Python interpreter.
(2) Directly inputting a variable in the interpreter calls the repr function by default, while print(var) calls the str function by default.
(3) The return value of the repr function can generally be restored to an object using the eval function.
(4) The two call the built-in functions str() and repr() of the object respectively.
Tip 35: Distinguish the use cases of staticmethod and classmethod.
Library Usage
Tip 36: Master the basic usage of strings.
Tip 37: Choose between sort() and sorted() functions as needed.
sort() sorts the list in place, so it cannot sort tuples or other immutable types.
sorted() can sort any iterable type without changing the original variable.
Tip 38: Use the copy module for deep copying objects, distinguishing between shallow copy and deep copy.
Tip 39: Use Counter for counting statistics; Counter is a subclass of dictionary in the collections module.
Tip 40: Deeply master ConfigParse.
Tip 41: Use the argparse module to handle command-line arguments.
Tip 42: Use pandas to handle large CSV files.
Python itself provides a CSV file handling module with functions like reader and writer.
Pandas can provide chunking and merging processing, suitable for large data volumes, and is more convenient for two-dimensional data operations.
Tip 43: Use ElementTree to parse XML.
Tip 44: Understand the pros and cons of the pickle module.
Advantages: Simple interface, cross-platform compatibility, wide range of supported data types, strong extensibility.
Disadvantages: Does not guarantee atomicity of data operations, has security issues, and is not compatible between different languages.
Tip 45: Another choice for serialization is the JSON module: load and dump operations.
Tip 46: Use traceback to get stack information.
Tip 47: Use logging to record log information.
Tip 48: Use the threading module to write multi-threaded programs.
Tip 49: Use the Queue module to make multi-threaded programming safer.
Design Patterns
Tip 50: Use modules to implement the singleton pattern.
Tip 51: Use the mixin pattern to make programs more flexible.
Tip 52: Use the publish-subscribe pattern to achieve loose coupling.
Tip 53: Use the state pattern to beautify code.
Internal Mechanisms
Tip 54: Understand built-in objects.
Tip 55: __init__()
is not a constructor; understand the difference between new() and it.
Tip 56: Understand the variable lookup mechanism, i.e., scope.
Local scope
Global scope
Nested scope
Built-in scope
Tip 57: Why is the self parameter needed?
Tip 58: Understand MRO (Method Resolution Order) and multiple inheritance.
Tip 59: Understand the descriptor mechanism.
Tip 60: Distinguish between getattr() and getattribute() methods.
Tip 61: Use the more secure property.
Tip 62: Master metaclasses.
Tip 63: Familiarize yourself with Python object protocols.
Tip 64: Use operator overloading to implement infix syntax.
Tip 65: Familiarize yourself with Python’s iterator protocol.
Tip 66: Familiarize yourself with Python generators.
Tip 67: Understand coroutines and greenlets based on generators, and the differences between coroutines, multithreading, and multiprocessing.
Tip 68: Understand the limitations of GIL.
Tip 69: Object management and garbage collection.
Using Tools to Assist Project Development
Tip 70: Install third-party packages from PyPI.
Tip 71: Use pip and yolk to install and manage packages.
Tip 72: Use paster to create packages.
Tip 73: Understand the concept of unit testing.
Tip 74: Write unit tests for packages.
Tip 75: Use Test-Driven Development (TDD) to improve code testability.
Tip 76: Use Pylint to check code style.
Code style review.
Code error checking.
Identify duplicate and unreasonable code for easier refactoring.
Highly configurable and customizable.
Supports integration with various IDEs and editors.
Can generate UML diagrams based on Python code.
Can be combined with continuous integration tools like Jenkins to support automated code review.
Tip 77: Conduct efficient code reviews.
Tip 78: Publish packages to PyPI.
Performance Profiling and Optimization
Tip 79: Understand the basic principles of code optimization.
Tip 80: Use performance optimization tools.
Tip 81: Use cProfile to locate performance bottlenecks.
Tip 82: Use memory_profiler and objgraph to analyze memory usage.
Tip 83: Strive to reduce algorithm complexity.
Tip 84: Master basic techniques for loop optimization.
Reduce calculations inside loops.
Convert explicit loops to implicit loops, though this sacrifices code readability.
Refer to local variables as much as possible within loops.
Pay attention to inner nested loops.
Tip 85: Use generators to improve efficiency.
Tip 86: Use different data structures to optimize performance.
Tip 87: Make full use of the advantages of sets.
Tip 88: Use the multiprocessing module to overcome GIL limitations.
Tip 89: Use thread pools to improve efficiency.
Tip 90: Use Cython to write extension modules.
万水千山总是情,点个 👍 行不行。
Text / Southern
Images / Southern
Layout / Southern
Click below
Follow us