Fundamentals 15 min read

Comprehensive Guide to Python Best Practices and Coding Techniques

This article presents a thorough collection of Python best‑practice recommendations, covering coding style, language features, standard library usage, design patterns, testing, performance profiling, and tooling to help developers write clean, efficient, and maintainable Python code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Comprehensive Guide to Python Best Practices and Coding Techniques

1. First

Suggestion 1: Understand the Pythonic concept.

Suggestion 2: Write Pythonic code.

(1) Avoid non‑standard code such as using only case‑sensitive variable names, confusing identifiers, or fearing long variable names; sometimes longer names improve readability.

(2) Deeply study Python language features and libraries, e.g., the evolution of Python and popular Pythonic libraries like Flask.

Suggestion 3: Understand differences between Python and C (indentation vs. braces, single vs. double quotes, ternary operator, lack of switch‑case).

Suggestion 4: Add appropriate comments in code.

Suggestion 5: Insert blank lines to make code layout more reasonable.

Suggestion 6: Follow four principles when writing functions.

(1) Keep functions short and avoid deep nesting.

(2) Design function signatures to be reasonable, simple, and easy to use.

(3) Design function parameters with backward compatibility in mind.

(4) A function should do one thing; keep granularity consistent.

Suggestion 7: Centralize constants in a single file and use all‑uppercase names.

2. Programming Idioms

Suggestion 8: Use assert statements to discover problems, but be aware they affect performance.

Suggestion 9: Swap values directly with a, b = b, a instead of using a temporary variable.

Suggestion 10: Leverage lazy evaluation to avoid unnecessary calculations.

Suggestion 11: Understand the drawbacks of enum alternatives (Python now has built‑in Enum).

Suggestion 12: Avoid using type for type checking; prefer isinstance when needed.

Suggestion 13: Convert operands to float before division (not needed in Python 3).

Suggestion 14: Beware of security risks of eval() , similar to SQL injection.

Suggestion 15: Use enumerate() to get both index and value while iterating.

Suggestion 16: Distinguish when to use == versus is , especially for immutable types.

Suggestion 17: Prefer Unicode; Python 2’s encoding issues are largely gone in Python 3.

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

3. Basic Usage

Suggestion 19: Use from … import sparingly to avoid polluting the namespace.

Suggestion 20: Prefer absolute imports (relative imports are removed in Python 3).

Suggestion 21: i += 1 is not the same as ++i ; the latter is just a unary plus in Python.

Suggestion 22: Use with to automatically close resources, especially for file I/O.

Suggestion 23: Use else clauses to simplify loops and exception handling.

Suggestion 24: Follow basic principles of exception handling.

(1) Keep the try block small.

(2) Prefer specific exception clauses over a bare except or except Exception .

(3) Handle exceptions at the appropriate level.

(4) Provide clear exception messages following parameter conventions.

Suggestion 25: Avoid pitfalls in finally blocks.

Suggestion 26: Understand None and correctly test for emptiness.

Suggestion 27: Use str.join() for string concatenation instead of the + operator.

Suggestion 28: Prefer the format() method over the % operator for string formatting.

Suggestion 29: Distinguish mutable and immutable objects, especially when used as function arguments.

Suggestion 30: Use consistent container literals ( [] , {} , () ) and list comprehensions for clearer and more efficient code.

Suggestion 31: Understand that function arguments are passed by object reference, not by value or by reference.

Suggestion 32: Beware of default argument pitfalls, especially when the default is a mutable object.

Suggestion 33: Use variable‑length arguments ( *args , **kwargs ) judiciously; they can obscure the function signature.

(1) Over‑flexible use makes signatures unclear and reduces readability.

(2) If many arguments are needed, consider refactoring the function.

Suggestion 34: Distinguish between str() and repr() .

(1) str() is user‑friendly; repr() is developer‑oriented and aims for an unambiguous representation.

(2) The interactive interpreter calls repr() , while print() uses str() .

(3) repr() output can often be fed to eval() to recreate the object.

(4) Internally they invoke __str__() and __repr__() respectively.

Suggestion 35: Know when to use staticmethod versus classmethod .

4. Library Usage

Suggestion 36: Master basic string operations.

Suggestion 37: Choose between sort() (in‑place) and sorted() (returns a new sorted iterable).

Suggestion 38: Use the copy module to differentiate shallow and deep copies.

Suggestion 39: Use collections.Counter for counting.

Suggestion 40: Master configparser for configuration files.

Suggestion 41: Use argparse to handle command‑line arguments.

Suggestion 42: Use pandas for processing large CSV files, benefiting from chunking and merging.

Suggestion 43: Parse XML with xml.etree.ElementTree .

Suggestion 44: Understand the advantages and disadvantages of the pickle module.

Advantage: simple API, cross‑platform, supports many data types, extensible.

Disadvantage: no atomicity guarantees, security concerns, language incompatibility.

Suggestion 45: Use the json module for serialization (load/dump).

Suggestion 46: Retrieve stack traces with traceback .

Suggestion 47: Record logs using the logging module.

Suggestion 48: Write multithreaded programs with the threading module.

Suggestion 49: Use the queue module to make multithreading safer.

5. Design Patterns

Suggestion 50: Implement the Singleton pattern using modules.

Suggestion 51: Use mixins to increase flexibility.

Suggestion 52: Apply the publish‑subscribe pattern for loose coupling.

Suggestion 53: Use the State pattern to improve code clarity.

6. Internal Mechanisms

Suggestion 54: Understand built‑in objects.

Suggestion 55: __init__() is not the constructor; know the difference between __new__() and __init__() .

Suggestion 56: Grasp variable lookup rules (scopes).

Local scope, global scope, nested scope, built‑in scope.

Suggestion 57: Know why the self parameter is required.

Suggestion 58: Understand Method Resolution Order (MRO) and multiple inheritance.

Suggestion 59: Understand descriptor protocol.

Suggestion 60: Differentiate __getattr__() from __getattribute__() .

Suggestion 61: Use safer property implementations.

Suggestion 62: Master metaclasses.

Suggestion 63: Familiarize yourself with Python’s object protocol.

Suggestion 64: Overload operators to achieve infix syntax.

Suggestion 65: Understand the iterator protocol.

Suggestion 66: Master generators.

Suggestion 67: Use generator‑based coroutines (greenlet) and understand differences among coroutines, threads, and processes.

Suggestion 68: Recognize the limitations of the Global Interpreter Lock (GIL).

Suggestion 69: Manage objects and garbage collection.

7. Tool‑Assisted Development

Suggestion 70: Install third‑party packages from PyPI.

Suggestion 71: Manage packages with pip and yolk .

Suggestion 72: Use paster to create packages.

Suggestion 73: Understand unit testing concepts.

Suggestion 74: Write unit tests for packages.

Suggestion 75: Apply Test‑Driven Development (TDD) to improve testability.

Suggestion 76: Use Pylint for style checking.

Code style review, error detection, duplicate detection, refactoring assistance, IDE integration, UML generation, CI integration (e.g., Jenkins).

Suggestion 77: Conduct efficient code reviews.

Suggestion 78: Publish packages to PyPI.

8. Performance Profiling and Optimization

Suggestion 79: Understand basic principles of code optimization.

Suggestion 80: Leverage performance‑optimization tools.

Suggestion 81: Use cProfile to locate bottlenecks.

Suggestion 82: Profile memory with memory_profiler and objgraph .

Suggestion 83: Reduce algorithmic complexity.

Suggestion 84: Master loop‑optimization techniques.

Reduce calculations inside loops, replace explicit loops with implicit ones when appropriate, keep frequently used variables local, watch nested loops.

Suggestion 85: Use generators to improve efficiency.

Suggestion 86: Choose appropriate data structures for performance.

Suggestion 87: Exploit the advantages of set .

Suggestion 88: Use the multiprocessing module to overcome GIL limitations.

Suggestion 89: Employ thread pools for better throughput.

Suggestion 90: Write extension modules with Cython.

design patternsperformancepythonTestingbest-practicestoolingcoding style
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.