Understanding Python Decorators in 12 Easy Steps!
Ok, perhaps I jest. As a Python instructor, understanding decorators is a topic I find students consistently struggle with upon first exposure. That’s because decorators are hard to understand! Getting decorators requires understanding several functional programming concepts as well as feeling comfortable with some unique features of Python’s function definition and function calling syntax. *Using* decorators is easy (see Section 10)! But writing them can be complicated. I can’t make decorators easy - but maybe by walking through each piece of the puzzle one step at a time I can help you feel more confident in understanding decorators. I should also note that I used Python’s doctest modules to run the Python code samples in this article. 1. Functions in Python are created with the def keyword and take a name and an optional list of parameters. >>> def foo():... return 1>>> foo()1 2. In Python functions create a new scope. 3. variable resolution rules 4. 5. Whoo! 6. 7. 8. 9. 10. 11.
Related: Help and Tips