Skip to Content
Clean Code in Python
book

Clean Code in Python

by Mariano Anaya
August 2018
Intermediate to advanced
332 pages
9h 12m
English
Packt Publishing
Content preview from Clean Code in Python

Decorate functions

Functions are probably the simplest representation of a Python object that can be decorated. We can use decorators on functions to apply all sorts of logic to them—we can validate parameters, check preconditions, change the behavior entirely, modify its signature, cache results (create a memorized version of the original function), and more.

As an example, we will create a basic decorator that implements a retry mechanism, controlling a particular domain-level exception and retrying a certain number of times:

# decorator_function_1.pyclass ControlledException(Exception): """A generic exception on the program's domain.""" def retry(operation): @wraps(operation) def wrapped(*args, **kwargs): last_raised = None RETRIES_LIMIT ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Clean Code in Python - Second Edition

Clean Code in Python - Second Edition

Mariano Anaya
Python for Programmers

Python for Programmers

Paul Deitel, Harvey Deitel

Publisher Resources

ISBN: 9781788835831Supplemental Content