Skip to Content
Secret Recipes of the Python Ninja
book

Secret Recipes of the Python Ninja

by Cody Jackson
May 2018
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 37m
English
Packt Publishing
Content preview from Secret Recipes of the Python Ninja

How to do it...

This walk through shows how to create a decorator that can be used to check arguments passed to a function. This can be handled in a number of different ways, such as if...else checks, assert statements, and so on, but, by using a decorator, we can use this code on any function that operates the same way:

  1. First, we have to decide what the decorator will do. For this use case, the decorator function will look at arguments being passed to a function and check whether the values passed are integers.
  2. Write the decorator function just as you would write any other function:
        def arg_check(func):            def wrapper(num):                if type(num) != int:                    raise TypeError("Argument is not an integer")                elif num <= 0: raise ValueError("Argument is not ...
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

The Expanding World of Python

The Expanding World of Python

Dane Hillard

Publisher Resources

ISBN: 9781788294874Supplemental Content