90 Practical Python Programming Tips

Source: Internet

Coding Principles

Tip 1: Understand the concept of Pythonic—see The Zen of Python in Python.

Tip 2: Write Pythonic code.

(1) Avoid non-standard code, such as using case sensitivity 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. Explore one or two industry-recognized Pythonic codebases, such as Flask.

Tip 3: Understand the differences between Python and C, such as indentation vs. {}, single vs. double quotes, ternary operators, and switch-case statements.

Tip 4: Add comments appropriately 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 as short as possible, with no excessive nesting.

(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, ensuring consistency in function granularity.

Tip 7: Concentrate constants in one file, and use uppercase letters for constant names.

Programming Idioms

Tip 8: Use assert statements to identify issues, but be aware that assertions can affect performance.

Tip 9: When exchanging values, avoid using temporary variables; instead, use a, b = b, a.

Tip 10: Take full advantage of lazy evaluation to avoid unnecessary calculations.

Tip 11: Understand the flaws of using enumeration instead of implementation (the latest version of Python has added enumeration features).

Tip 12: Avoid using type for type checking, as the result may not always be reliable. If necessary, use isinstance instead.

Tip 13: Convert variables to float before performing division (not a concern after Python 3).

Tip 14: Be wary of security vulnerabilities in eval(), which can be similar to SQL injection.

Tip 15: Use enumerate() to get both the index and value during sequence iteration.

Tip 16: Distinguish between == and is in applicable scenarios, especially when comparing strings and other immutable types (see comments for details).

Tip 17: Prefer using Unicode. In Python 2, encoding can be troublesome, but Python 3 alleviates many concerns.

Tip 18: Build a reasonable package hierarchy to manage modules.

Programming Idioms 2

Tip 19: Use from…import statements judiciously to prevent namespace pollution.

Tip 20: Prefer using absolute imports to import modules (relative imports have been removed in Python 3).

Tip 21: i += 1 is not equal to ++i; in Python, the ++ sign before i only indicates positivity, not an operation.

Tip 22: Habitually use with to automatically close resources, especially in file I/O.

Tip 23: Use else clauses to simplify loops (exception handling).

Tip 24: Follow some basic principles for exception handling:

(1) Pay attention to the granularity of exceptions; minimize code in the try block.

(2) Be cautious with standalone except statements or except Exception statements; instead, target specific exceptions.

(3) Be mindful of the order of exception handling and handle exceptions at the appropriate level.

(4) Use more user-friendly exception messages and adhere to the specifications for exception parameters.

Tip 25: Avoid potential pitfalls in finally.

Tip 26: Deeply understand None and correctly determine whether an object is empty.

Tip 27: Prefer using join for concatenating strings rather than the + operator.

Tip 28: When formatting strings, prefer using the format function instead of the % format.

Tip 29: Treat mutable and immutable objects differently, especially when used as function parameters.

Tip 30: Use consistent container initialization forms with [], {}, and (). List comprehensions can make the code clearer and more efficient.

Tip 31: Function parameters are not passed by value or reference, but rather by object or object reference.

Tip 32: Be wary of potential issues with default parameters, especially when the default parameter is a mutable object.

Tip 33: Use variable-length parameters *args and **kwargs cautiously:

(1) Such usage can be too flexible, making function signatures unclear and harder to read.

(2) If a function is simplified using variable-length parameters due to too many parameters, it may be a candidate for refactoring.

Tip 34: Deeply understand the differences between str() and repr():

(1) The goals of the two are different: str is mainly for end-users, aiming for readability, returning a user-friendly string; while repr is for Python interpreters or developers, aiming for accuracy, returning a value that represents the internal definition of the Python interpreter.

(2) Directly inputting a variable in the interpreter defaults to calling the repr function, while print(var) defaults to calling the str function.

(3) The return value of the repr function can generally be restored to an object using the eval function.

(4) Both call the built-in functions str() and repr() of the object.

Tip 35: Distinguish between the usage scenarios of static methods staticmethod and class methods classmethod.

Library Usage

Tip 36: Master the basic usage of strings.

Tip 37: Choose between sort() and sorted() functions as needed:

sort() sorts a list in place, so it cannot sort tuples or other immutable types.

sorted() can sort any iterable type without altering 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 dict 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 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, security issues, and incompatibility between different languages.

Tip 45: Another option for serialization is the JSON module: load and dump operations.

Tip 46: Use traceback to obtain 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 the 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, that is, scope:

Local scope

Global scope

Nested scope

Built-in scope

Tip 57: Why is the self parameter necessary?

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 safer property.

Tip 62: Master metaclasses.

Tip 63: Familiarize yourself with Python object protocols.

Tip 64: Use operator overloading to achieve infix syntax.

Tip 65: Familiarize yourself with Python’s iterator protocol.

Tip 66: Familiarize yourself with Python’s generators.

Tip 67: Understand coroutines and greenlets based on generators, distinguishing between coroutines, multithreading, and multiprocessing.

Tip 68: Understand the limitations of GIL (Global Interpreter Lock).

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: Create packages using paster.

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 integrate with continuous integration tools like Jenkins for automated code reviews.

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: Utilize performance optimization tools.

Tip 81: Use cProfile to identify 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 may sacrifice code readability.

Reference local variables inside loops as much as possible.

Pay attention to inner nested loops.

Tip 85: Use generators to improve efficiency.

Tip 86: Optimize performance using different data structures.

Tip 87: Fully utilize 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.

--End--

Students who want discounts on books can look at: Discount book purchasing channels


Leave a Comment