Jiaxi Liu (Jesse)

Master’s Graduate

Software Engineer | Scalable APIs · Web Scraping · Data Integration · Code Quality & Refactoring

Back to Blog

Python and Flask Review: Decorators, Generators, Copying, Magic Methods, Encryption, and Tokens

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:

  1. User logs in
  2. Server verifies credentials
  3. Server returns a token
  4. Later requests include the token
  5. Server validates the token and returns resources

In real systems, use HTTPS, expiration, and permission checks.