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. 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 The body of the function (as with all multi-line statements in Python) is mandatory and indicated by indentation. 2. In Python functions create a new scope. 3. variable resolution rules