Python Decorators: Functions là First-Class Objects

Python Decorators: Functions là First-Class Objects
Decorators là một trong những tính năng elegant nhất của Python, cho phép bạn modify hoặc enhance functions và classes mà không thay đổi source code của chúng. Chúng thiết yếu cho frameworks như Flask, FastAPI, và Django, và hiểu chúng mở khóa các programming patterns mạnh mẽ. Hướng dẫn này đưa bạn từ fundamentals của first-class functions đến advanced decorator patterns.
Những Gì Bạn Sẽ Học
✅ Functions như first-class objects
✅ Closures và scope
✅ Function wrappers và decorators
✅ Cú pháp decorator với @
✅ Decorators với arguments
✅ Class decorators
✅ Các decorator patterns phổ biến
✅ functools.wraps và bảo toàn metadata
Điều Kiện Tiên Quyết
Trước khi tìm hiểu decorators, bạn nên hiểu:
- Python functions từ Giai Đoạn 1: Nền Tảng
- Lập trình hướng đối tượng từ Giai Đoạn 2: OOP & Tính Năng Nâng Cao
Ghi chú: Phần này chứa các ví dụ code tương tự phiên bản tiếng Anh. Để tiết kiệm không gian, chúng tôi tập trung vào giải thích khái niệm bằng tiếng Việt và giữ nguyên code examples.
1. Functions như First-Class Objects
Trong Python, functions là first-class objects - chúng có thể: được gán cho variables, passed như arguments cho functions khác, returned từ functions, và stored trong data structures. Đây là foundation để hiểu decorators. Functions có thể được assign cho variables, passed như arguments, returned từ functions. Đây là nền tảng cho closures và decorators.
2. Hiểu Closures
Closure là function capture và remember variables từ enclosing scope của nó, ngay cả sau khi scope đó finished executing. Closures giữ reference đến variables từ outer scope. Dùng nonlocal keyword để modify enclosed variables. Closures là cơ chế mà decorators "wrap" functions trong khi preserve access đến original function và decorator arguments.
3. Basic Function Decorators
Decorator là function nhận another function và extends behavior của nó mà không explicitly modify nó. Decorator pattern: function nhận function, returns wrapper function. Syntax @decorator là syntactic sugar cho func = decorator(func). Wrapper function thường dùng *args, **kwargs để work với any function signature.
4. Practical Decorator Examples
Timing decorator: Đo execution time của functions với time.time() before và after call.
Logging decorator: Log function calls với arguments và return values. Hữu ích cho debugging và monitoring.
Retry decorator: Tự động retry failed operations với configurable max attempts và delay. Essential cho unreliable external services.
Tất cả examples dùng @wraps để preserve original function metadata.
5. Decorators với Arguments
Để tạo decorators accept arguments, cần extra layer of nesting: decorator factory returns decorator, decorator returns wrapper. Pattern: outer function nhận decorator arguments, returns actual decorator, decorator returns wrapper function. Ví dụ: @repeat(times=3) - repeat là decorator factory nhận times argument.
6. Stacking Multiple Decorators
Có thể apply nhiều decorators cho single function. Decorators execute từ bottom to top (closest đến function first). Order matters! Thứ tự apply decorators ảnh hưởng đến behavior. Ví dụ: @timer @log_call @validate - validate chạy first, log second, timer last.
7. Class Decorators
Decorators cũng có thể modify classes. Singleton pattern: Decorator ensure chỉ một instance của class tồn tại. Adding methods: Decorator có thể add new methods hoặc modify existing methods của class. Class decorators nhận class làm argument, return modified class hoặc wrapper.
8. functools.wraps - Preserving Metadata
Luôn dùng @wraps từ functools để preserve original function's metadata như __name__, __doc__, __annotations__. Không dùng @wraps → wrapper function mất original metadata. Best practice: mọi decorator nên dùng @wraps(func) trong wrapper definition.
9. Real-World Example: API Rate Limiter
Example kết hợp nhiều decorator concepts: class-based decorator với __call__ method, closure để track call history, time window tracking, exception raising khi exceed limit. Demonstrates production-quality decorator implementation với configurable max_calls và period parameters.
10. Common Decorator Patterns
Authentication decorator: Check user authentication trước khi execute function. Raise PermissionError nếu not authenticated.
Caching/memoization decorator: Store function results in cache dict để avoid recomputation. Check cache trước, execute và cache nếu miss. Note: functools.lru_cache là built-in alternative tốt hơn.
Deprecation warning decorator: Emit warnings cho deprecated functions. Dùng warnings.warn() với DeprecationWarning category.
11. Best Practices
✅ Do's:
- Always dùng
@wrapsđể preserve metadata - Accept
*args, **kwargscho flexibility - Dùng type hints cho decorators
- Document decorators với clear usage examples
❌ Don'ts:
- Không forget
@wraps- loses function metadata - Không dùng decorators cho complex logic - keep simple
- Không modify arguments unless documented - surprising behavior
12. Common Pitfalls
Order matters: Decorators apply bottom-to-top. @a @b def func() → func = a(b(func)).
Decorating methods: Wrapper function nhận self như first argument khi decorate methods.
Return value: Always return result từ wrapper. Forget return → function returns None.
Summary
Trong guide này, bạn đã học:
✅ Functions như first-class objects trong Python
✅ Closures và cách chúng capture enclosing scope
✅ Tạo basic function decorators
✅ Dùng @ syntax cho clean code
✅ Decorators với arguments (nested decorators)
✅ Class decorators cho modifying classes
✅ functools.wraps cho preserving metadata
✅ Common patterns: timing, logging, retry, auth, caching
✅ Best practices và common pitfalls
Decorators là thiết yếu cho frameworks như Flask, FastAPI, và Django, và hiểu chúng cho phép bạn viết code cleaner, more modular.
Bước Tiếp Theo
Giờ bạn đã hiểu decorators, khám phá các chủ đề liên quan:
Thêm Python Deep Dives:
- Type Hints & Typing - Type-safe decorators
- Async Programming - Async decorators
- Python Testing với pytest - Testing decorated functions
Áp Dụng Decorators trong Web Development:
- FastAPI Learning Roadmap - FastAPI sử dụng decorators extensively
Quay Lại Roadmap:
- Python Learning Roadmap - Lộ trình học hoàn chỉnh
- Giai Đoạn 2: OOP & Tính Năng Nâng Cao - Nơi decorators được giới thiệu
Thuộc chuỗi bài Lộ Trình Học Python
📬 Đăng ký nhận bản tin
Nhận những bài viết mới nhất qua email mỗi tuần. Không spam, hủy đăng ký bất cứ lúc nào.
Chúng tôi tôn trọng quyền riêng tư của bạn. Hủy đăng ký bất cứ lúc nào.
💬 Comments
Đăng nhập để bình luận
Chúng tôi sẽ không đăng bất cứ điều gì mà không có sự cho phép của bạn.