Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

python - 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)
question from:https://stackoverflow.com/questions/25829364/applying-a-decorator-to-an-imported-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...