Python fundamentals often appear in backend interviews and automation scripting.
Decorators
A decorator is a function that takes a function and returns a new function.
def log(fn):
def wrapper(*args, **kwargs):
print("before")
result = fn(*args, **kwargs)
print("after")
return result
return wrapper
@log
def hello():
print("hello")@log is equivalent to hello = log(hello).
Generators
Generators use yield and produce values lazily.
def count():
yield 1
yield 2
for item in count():
print(item)They are useful for large data streams because they avoid loading everything at once.
Shallow Copy and Deep Copy
Shallow copy copies only the first level. Nested references are still shared. Deep copy recursively copies nested objects.
import copy
a = [[1], [2]]
b = copy.copy(a)
c = copy.deepcopy(a)Magic Methods
Common magic methods:
__init__: initialize an object__new__: create an object__del__: called when an object is destroyed__str__: string representation
Flask, Encryption, and Tokens
Flask is a lightweight Python web framework. A common token authentication flow:
- User logs in
- Server verifies credentials
- Server returns a token
- Later requests include the token
- Server validates the token and returns resources
In real systems, use HTTPS, expiration, and permission checks.