Ultimate Python Cheat Sheet: From Py2 vs Py3 Differences to Advanced Concurrency and Design Patterns
This comprehensive guide compiles essential Python knowledge—including Python 2 vs 3 changes, conversion tools, frequently used libraries, concurrency models, testing techniques, core language concepts, plus related topics such as networking, MySQL, Redis, Linux, design patterns, data structures, algorithms, and interview‑level questions—providing a one‑stop reference for developers seeking to deepen their Python expertise.
Python 2 vs Python 3
print became a function; in Python 2 it was a keyword.
unicode is the default string type; no separate unicode object.
Division (/) always returns a float.
long type was removed.
xrange no longer exists; range now behaves like xrange.
Chinese identifiers are allowed.
Advanced unpacking and * unpacking.
Keyword‑only arguments require name=value after *.
raise from for exception chaining.
dict.items() replaces iteritems.
yield from to delegate to sub‑generators.
asyncio, async/await provide native coroutine support.
New modules: enum, mock, ipaddress, concurrent.futures, asyncio, urllib, selectors.
Python 2/3 Conversion Tools
six – compatibility library for both versions.
2to3 – rewrites syntax to Python 3.
__future__ imports – enable upcoming features.
Commonly Used Libraries
collections – essential data structures (see SegmentFault link).
heapq – heap‑based priority queue and sorting.
itertools – advanced iterator utilities (see SegmentFault link).
Less Common but Important Libraries
dis – bytecode analysis.
inspect – introspection of generators and objects.
cProfile – performance profiling.
bisect – maintain sorted lists.
fnmatch – filename pattern matching (case‑sensitive vs case‑insensitive).
timeit – measure execution time of small code snippets.
Context Managers and Advanced Types
from contextlib import contextmanager
@contextmanager
def my_context():
# generator becomes a context manager
yieldTypes Module
import types
# types.coroutine makes a generator behave like a coroutineHTML Escaping
import html
escaped = html.escape("<h1>I'm Jim</h1>")
unescaped = html.unescape(escaped)Testing
unittest – subclass TestCase, use setUp/tearDown.
pytest – functions prefixed with test_, auto‑discover.
coverage – measure test coverage.
GIL (Global Interpreter Lock)
Released after a certain number of bytecode instructions or when I/O occurs.
CPU‑bound tasks benefit from multiprocessing; I/O‑bound tasks benefit from threading or asyncio.
Monkey Patching
from gevent import monkey
monkey.patch_all() # replace blocking functions with non‑blocking versionsIntrospection
Use id, type, isinstance to examine objects at runtime.
Parameter Passing
Python uses “shared” (object reference) passing; defaults are evaluated once.
Exception Blocks
else runs only when no exception occurs; finally always runs.
except can catch multiple exception types.
Cython
Translates Python code to C for performance gains.
Generators and Iterators
Iterable objects implement __iter__.
Iterator objects implement __next__ and __iter__.
Generators are special iterators created with yield.
Coroutines
Implemented via async/await or generator‑based yield.
Lightweight compared to threads.
Dictionary Internals
Implemented with a hash table; average lookup O(1).
CPython resolves collisions with quadratic probing.
Hash Table Expansion and Collision Resolution
Uses chaining or open addressing (quadratic probing).
Rehashes to a larger table when load factor grows.
Network Knowledge
HTTPS – encrypted HTTP over port 443, improves SEO.
Common status codes: 204, 206, 303, 304, 307, 401, 403, 400, 201, 503.
Idempotent and safe HTTP methods.
WSGI – simple callable interface (example provided).
RPC, CDN, SSL/TLS, SSH, TCP/UDP basics, three‑way handshake, four‑way termination.
XSS/CSRF mitigation via HttpOnly cookies.
MySQL
Index evolution: linear → binary search → hash → B‑tree variants.
InnoDB uses clustered primary key; MyISAM stores data separately.
When clearing a table, InnoDB deletes row by row; MyISAM recreates the table.
Text/BLOB columns cannot have default values.
Index can become ineffective with leading % LIKE, implicit type conversion, or not following left‑most prefix.
Aggregated index concepts: B+Tree leaf nodes store data pointers; primary key is clustered.
Redis
In‑memory, single‑threaded, event‑driven for high performance.
Data types: strings, lists, hashes, sets, sorted sets (zset), bitmaps, hyperloglog.
Persistence: RDB snapshots (SAVE/BGSAVE) and AOF logs.
Transactions via MULTI/EXEC/WATCH; pipelines for batch commands.
Distributed lock pattern using SETNX + EXPIRE and UUID values.
Common issues: cache snowball, cache penetration, cache warm‑up, cache downgrade.
LRU and LFU eviction policies.
Linux
Five I/O models: blocking, non‑blocking, multiplexed (select/poll/epoll), signal‑driven, asynchronous (gevent/asyncio).
Useful commands: tldr for concise manuals, top, free, kill -9 vs -15.
Memory management: paging (virtual memory) and segmentation.
Design Patterns
Singleton – implemented via decorator, metaclass, or __new__.
Factory – simple function returning class instances based on a string.
Builder – separates construction of complex objects (example with Computer).
Data Structures & Algorithms (Python Implementations)
Sorting: quick sort, selection sort, insertion sort, merge sort, heap sort (using heapq.nsmallest).
Stacks and queues – built with collections.deque.
Binary search – recursive implementation.
Linked list reversal, merging sorted lists, etc. (interview questions).
Interview‑Level Topics
Two‑stack queue implementation, linked‑list reversal, merging sorted lists, node deletion, binary‑tree inversion.
Short‑URL service design (62‑base encoding).
Seckill (flash‑sale) system design.
Choosing auto‑increment integer primary keys vs UUIDs in MySQL.
Distributed ID generation (e.g., Redis INCR).
Distributed lock reliability and handling node failures (consistent hashing).
Caching Algorithms
LRU – evicts least recently used items.
LFU – evicts least frequently used items.
Server‑Side Performance Optimization
Use proper data structures and algorithms.
Database tuning: index optimization, slow‑query elimination, batch operations, NoSQL caching.
Network I/O: batch requests, pipelines.
Cache layer: Redis.
Asynchronous processing: asyncio, Celery.
Concurrency: multithreading, gevent.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
