Comprehensive Python Knowledge Summary and Interview Guide
This article compiles an extensive Python cheat‑sheet covering language differences between Python 2 and 3, essential libraries, concurrency, data structures, design patterns, testing, performance tips, database and networking fundamentals, along with numerous code examples and interview insights for developers.
This document is a comprehensive Python knowledge base that includes language differences, useful libraries, advanced topics, design patterns, testing techniques, performance optimization, and interview preparation material.
Python 2 vs Python 3
print is a function in Python 3.
unicode is the default string type in Python 3.
range replaces xrange.
new syntax such as async/await and yield from.
Additional built‑ins: enum, mock, ipaddress, concurrent.futures, asyncio, selector.
<code># Enum example
from enum import Enum
class COLOR(Enum):
YELLOW = 1
GREEN = 1 # alias
BLACK = 3
RED = 4
print(COLOR.GREEN) # COLOR.YELLOW
for i in COLOR.__members__.items():
print(i)
</code>Conversion Tools
six module for compatibility.
2to3 for syntax conversion.
__future__ imports for forward‑compatible features.
Common Libraries
collections – essential data structures.
heapq – priority queue and heap operations.
itertools – advanced iterator utilities.
contextlib – context manager helpers.
types – coroutine support with types.coroutine .
html – HTML escaping/unescaping.
unittest / pytest / coverage – testing frameworks.
Concurrency and Asynchronous Programming
ThreadPoolExecutor and ProcessPoolExecutor for parallelism.
asyncio event loop, tasks, futures, and cancellation.
Gevent monkey‑patching to make blocking calls non‑blocking.
<code># Asyncio example
import asyncio
async def fetch(url):
reader, writer = await asyncio.open_connection('example.com', 80)
writer.write(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')
data = await reader.read()
print(data.decode())
asyncio.run(fetch('http://example.com'))
</code>Multiprocessing Communication
Manager for shared data structures.
Pipe for two‑process communication.
Queue (and Manager().Queue) for process‑pool messaging.
<code># Pipe example
from multiprocessing import Pipe, Process
def producer(pipe):
pipe.send('msg')
def consumer(pipe):
print(pipe.recv())
if __name__ == '__main__':
recv, send = Pipe()
Process(target=producer, args=(send,)).start()
Process(target=consumer, args=(recv,)).start()
</code>Python Internals
LEGB name resolution order.
Mutable vs immutable objects, shallow vs deep copy.
Special methods: __getattr__, __getattribute__, __missing__, __new__.
GIL behavior and its impact on CPU‑bound vs I/O‑bound workloads.
Testing and Mocking
unittest.TestCase with setUp/tearDown.
pytest discovery conventions.
coverage for test coverage measurement.
Design Patterns
Singleton implementations (decorator, __new__, module‑level instance).
Factory function returning class instances.
Builder pattern for constructing complex objects.
<code># Singleton via __new__
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
</code>Data Structures & Algorithms
Sorting algorithms: quick sort, selection sort, insertion sort, merge sort, heap sort (using heapq).
Binary search implementation.
Stack and queue implementations with collections.deque.
<code># Quick sort example
def quick_sort(arr):
if len(arr) < 2:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
</code>Database Topics (MySQL)
Index evolution and B‑Tree structures.
When indexes become ineffective (LIKE '%x', functions on columns, OR conditions, low‑cardinality columns).
Difference between InnoDB (clustered index) and MyISAM (non‑clustered).
Common pitfalls: implicit type conversion, functions in WHERE clause, NOT/<> operators.
Redis Overview
In‑memory data store, single‑threaded event loop, multiple data types (string, list, hash, set, sorted set).
Persistence: RDB snapshots and AOF logs.
Transactions with MULTI/EXEC and pipelines.
Distributed lock pattern using SETNX + EXPIRE.
Cache issues: snowball, penetration, pre‑heat, eviction, downgrade.
<code># Distributed lock with Redis
import uuid, redis
r = redis.StrictRedis()
lock_key = 'my_lock'
lock_val = str(uuid.uuid4())
if r.set(lock_key, lock_val, nx=True, ex=10):
try:
# critical section
pass
finally:
if r.get(lock_key) == lock_val:
r.delete(lock_key)
</code>Linux & System Programming
Five I/O models: blocking, non‑blocking, multiplexing (select/poll/epoll), signal‑driven, asynchronous (aio/asyncio).
Process memory management: paging vs segmentation.
Common commands: top, free, kill -9 vs -15.
Networking Basics
HTTPS, HTTP status codes, request method idempotency.
TCP three‑way handshake and four‑step teardown, TIME_WAIT rationale.
WSGI application skeleton.
RPC, CDN, SSL/TLS, SSH basics.
Interview Tips & Advanced Questions
Design a URL shortener (base‑62 encoding).
Implement a flash‑sale system.
Generate distributed IDs (Redis INCR).
Explain cache consistency and distributed lock failure handling.
At the end of the article a promotional QR code invites readers to scan and receive free Python learning resources, including e‑books, tutorials, project code, and more.
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.