liveBook · Manning

Decorator

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A Python decorator is a callable construct that extends or modifies a function or method without changing its source definition.

Direct attribute access keeps a moving rectangle easy to read, but its coordinates still need boundary checks. Python property decorators put that behavior in methods without forcing callers to switch to explicit getter and setter calls. section 4.1.2

@property
    def x(self):
        return self._x
 
    @x.setter
    def x(self, value):
        if not (0 < value < SCREEN_WIDTH - self.width):
            self.dir_x = -self.dir_x
        self._x += abs(self._x - value) * self.dir_x

The `@property` method reads `x`; the `@x.setter` method handles a proposed value and reverses direction when it crosses a screen boundary. section 4.1.2

Decorators can also add behavior around a function call. A timing decorator returns a wrapper that starts a timer, calls the original function, reports elapsed time, and returns the result. Placing `@timing_decorator` above a function applies that wrapper while leaving the function’s body unchanged. section 4.1.2

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Works through property getters and setters plus a hand-written timing wrapper, without developing an exhaustive account of decorator behavior.
Examples
Shows a rectangle coordinate property and a timing decorator applied to a delayed task.
What it assumes
Assumes familiarity with Python functions, methods, and classes; introduces decorator syntax through concrete examples.
What you can do after
Apply it via Python’s `@property` and setter decorators to manage coordinates, or write a wrapper to time a function.
How it connects
Connects decorators to properties, getters, setters, attribute access, and wrapper functions.

Also explained in

Compare how 7 books explain decorator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.