Python Coding Principles, Best Practices, and Design Patterns
These comprehensive guidelines cover Pythonic concepts, coding conventions, function design, module organization, library usage, design patterns, internal mechanisms, development tools, performance profiling, and optimization techniques, providing developers with practical advice to write clean, efficient, and maintainable Python code.
Coding Principles
Advice 1: Understand the Pythonic concept – see "The Zen of Python".
Advice 2: Write Pythonic code; avoid non‑standard practices such as case‑only variable names, confusing identifiers, or overly short names, and prefer descriptive variable names when they improve readability.
Advice 3: Recognize differences between Python and C (indentation vs. braces, quoting rules, ternary operators, switch‑case equivalents).
Advice 4: Add appropriate comments in code.
Advice 5: Use blank lines to improve code layout.
Advice 6: Follow four principles when writing functions – keep them short, simple, and focused on a single task; design clear signatures; consider backward‑compatible parameters; and maintain consistent granularity.
Advice 7: Centralize constants in a dedicated file and name them in all caps.
Programming Idioms
Advice 8: Use assert statements for debugging, but be aware of the performance impact.
Advice 9: Swap values without a temporary variable using a, b = b, a .
Advice 10: Leverage lazy evaluation to avoid unnecessary calculations.
Advice 11: Understand the limitations of enum replacements; modern Python includes an enum module.
Advice 12: Prefer isinstance() over type() for type checking.
Advice 13: Convert operands to float before division (unnecessary in Python 3).
Advice 14: Beware of eval() security risks, similar to SQL injection.
Advice 15: Use enumerate() to obtain both index and value when iterating.
Advice 16: Distinguish between == and is , especially for immutable types.
Advice 17: Prefer Unicode strings; Python 2 required explicit handling, while Python 3 defaults to Unicode.
Advice 18: Build a sensible package hierarchy to manage modules.
Programming Idioms 2
Advice 19: Use from … import sparingly to avoid namespace pollution.
Advice 20: Prefer absolute imports; relative imports have been removed in Python 3.
Advice 21: i += 1 is not equivalent to ++i ; the latter merely denotes a positive sign.
Advice 22: Use with statements to automatically close resources, especially for file I/O.
Advice 23: Employ else clauses to simplify loops and exception handling.
Advice 24: Follow basic exception‑handling principles – keep try blocks small, catch specific exceptions, order catches appropriately, and provide clear error messages.
Advice 25: Avoid pitfalls in finally blocks.
Advice 26: Understand None and correctly test for emptiness.
Advice 27: Use str.join() for string concatenation instead of the + operator.
Advice 28: Prefer the format() method over the % operator for string formatting.
Advice 29: Treat mutable and immutable objects differently, especially when they are function arguments.
Advice 30: Use consistent container initialization ( [], {}, () ) and list comprehensions for clearer, more efficient code.
Advice 31: Function arguments are passed by object reference, not by value or by reference.
Advice 32: Beware of mutable default arguments.
Advice 33: Use variable‑length arguments ( *args , **kwargs ) judiciously; they can obscure function signatures.
Advice 34: Distinguish between str() (user‑friendly) and repr() (developer‑oriented) representations.
Advice 35: Know when to use staticmethod versus classmethod .
Library Usage
Advice 36: Master basic string operations.
Advice 37: Choose between list.sort() (in‑place) and sorted() (returns a new list) appropriately.
Advice 38: Use the copy module to differentiate shallow and deep copies.
Advice 39: Use collections.Counter for counting objects.
Advice 40: Become proficient with configparser .
Advice 41: Use argparse for command‑line argument parsing.
Advice 42: Process large CSV files with pandas ; the standard csv module also provides reader and writer .
Advice 43: Parse XML with xml.etree.ElementTree .
Advice 44: Understand the advantages and security concerns of the pickle module.
Advice 45: Use the json module for serialization (load/dump).
Advice 46: Retrieve stack traces with traceback .
Advice 47: Record logs using the logging module.
Advice 48: Write multithreaded programs with the threading module.
Advice 49: Use the queue module to make multithreading safer.
Design Patterns
Advice 50: Implement the Singleton pattern via modules.
Advice 51: Apply mixin classes for flexible code reuse.
Advice 52: Use publish‑subscribe for loose coupling.
Advice 53: Employ the State pattern to improve code clarity.
Internal Mechanisms
Advice 54: Understand built‑in objects.
Advice 55: Recognize that __init__() is not the constructor; __new__() creates the instance.
Advice 56: Grasp variable scope (local, global, nested, built‑in).
Advice 57: Know why the self parameter is required.
Advice 58: Understand MRO (method resolution order) and multiple inheritance.
Advice 59: Learn the descriptor protocol.
Advice 60: Differentiate getattr() from getattribute() .
Advice 61: Use the property decorator safely.
Advice 62: Master metaclasses.
Advice 63: Familiarize yourself with Python's object protocol.
Advice 64: Implement operator overloading for infix syntax.
Advice 65: Understand the iterator protocol.
Advice 66: Learn how generators work.
Advice 67: Use generator‑based coroutines (greenlet) and differentiate them from threads and processes.
Advice 68: Recognize the limitations of the GIL.
Advice 69: Manage objects and garbage collection.
Tool‑Assisted Development
Advice 70: Install third‑party packages from PyPI.
Advice 71: Manage packages with pip and yolk .
Advice 72: Create packages using paster .
Advice 73: Understand unit‑testing concepts.
Advice 74: Write unit tests for your packages.
Advice 75: Apply Test‑Driven Development (TDD) to improve testability.
Advice 76: Use Pylint for code‑style checking.
Advice 77: Conduct efficient code reviews.
Advice 78: Publish packages to PyPI.
Performance Profiling and Optimization
Advice 79: Learn basic code‑optimization principles.
Advice 80: Leverage performance‑optimization tools.
Advice 81: Use cProfile to locate bottlenecks.
Advice 82: Profile memory usage with memory_profiler and objgraph .
Advice 83: Strive to reduce algorithmic complexity.
Advice 84: Master loop‑optimization techniques (reduce inner‑loop work, prefer implicit loops when appropriate, use local variables).
Advice 85: Use generators to improve efficiency.
Advice 86: Choose suitable data structures for performance gains.
Advice 87: Exploit the advantages of set for fast membership tests.
Advice 88: Overcome GIL limitations with the multiprocessing module.
Advice 89: Use thread pools to increase throughput.
Advice 90: Write C extensions with Cython for speed‑critical code.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.