Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a decorator to an imported function?

I want to import a function:

from random import randint 

and then apply a decorator to it:

@decorator randint 

I was wondering if there was some syntactic sugar for this (like what I have above), or do I have to do it as follows:

@decorator def randintWrapper(*args):     return random.randint(*args) 
like image 872
killajoule Avatar asked Sep 14 '14 01:09

killajoule


People also ask

Can we use decorator inside a function in Python?

Nesting means placing or storing inside the other. Therefore, Nested Decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates the several effects together.

What is a function decorator?

By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. This sounds confusing, but it's really not, especially after you've seen a few examples of how decorators work. You can find all the examples from this article here.

What is the correct syntax for using a decorator?

Decorators use a special syntax in JavaScript, whereby they are prefixed with an @ symbol and placed immediately before the code being decorated.


1 Answers

Decorators are just syntactic sugar to replace a function object with a decorated version, where decorating is just calling (passing in the original function object). In other words, the syntax:

@decorator_expression def function_name():     # function body 

roughly(*) translates to:

def function_name():     # function body function_name = decorator_expression(function_name) 

In your case, you can apply your decorator manually instead:

from random import randint  randint = decorator(randint) 

(*) When using @<decorator> on a function or class, the result of the def or class definition is not bound (assigned to their name in the current namespace) first. The decorator is passed the object directly from the stack, and only the result of the decorator call is then bound.

like image 89
Martijn Pieters Avatar answered Sep 20 '22 10:09

Martijn Pieters