Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How python uses the wrapt module to write a flatter decorator

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces python how to use the wrapt module to write a more flat decorator, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian with you to understand.

Use wrapt modules to write flatter decorators

Have you ever encountered anything unpleasant in the process of writing the decorator? Whether you have it or not, I do. When I write code, I am often upset by the following two things:

1. When implementing a decorator with parameters, layer upon layer of nested function code is very difficult to write and read.

two。 Because of the difference between functions and class methods, decorators written for the former often cannot be applied directly to the latter

For example, in the following example, I implemented a decorator that generates random numbers and injects them as function parameters.

Import randomdef provide_number (min_num, max_num): decorator: randomly generates an integer in the range of [min_num, max_num] Append to the function's first positional parameter "" def wrapper (func): def decorated (* args, * * kwargs): num = random.randint (min_num, max_num) # call the function return func (num, * args, * * kwargs) return decorated return wrapper@provide_number (1) after appending num as the first argument Def print_random_number (num): print (num) # output random integers from 1 to 100. OUTPUT: 72print_random_number () @ provide_number decorator looks good But it has two problems that I mentioned earlier: the nesting level is deep and cannot be used on class methods. If you decorate a class method with it directly, the following occurs: class Foo: @ provide_number (1,100) def print_random_number (self, num): print (num) # OUTPUT: Foo (). Print_random_number ()

The print_random_number method in the Foo class instance will output the class instance self instead of the random number num we expect.

This result occurs because class methods (method) and functions (function) are slightly different in how they work. If you want to fix this problem, the provider_number decorator must cleverly skip the class instance self variable hidden in * args when modifying the position parameters of class methods in order to correctly inject num as the first parameter.

At this point, it's time for the wrapt module to make its debut. The wrapt module is a library of tools designed to help you write decorators. With it, we can easily transform the provide_number decorator and perfectly solve the problems of "deep nesting level" and "non-generality".

Import wraptdef provide_number (min_num, max_num): @ wrapt.decorator def wrapper (wrapped, instance, args, kwargs): # Parameter meaning: # #-wrapped: decorated function or class method #-instance: #-if the decorated is a normal class method, the value is a class instance #-if the decorated is a classmethod class method The value is class #-if the decorated is a class / function / static method This value is None # #-args: the position parameter of the call (note that there is no * symbol) #-kwargs: the keyword parameter of the call (note that there is no * * symbol) # num = random.randint (min_num, max_num) # Don't worry about whether wrapped is a class method or an ordinary function Directly append the parameter args = (num,) + args return wrapped (* args, * * kwargs) return wrapper# OUTPUT: 48Foo () .print_random_number () to the header

Decorators written in the wrapt module have the following advantages over the original:

Fewer nesting levels: you can reduce two levels of nesting to one using @ wrapt.decorator

Simpler: special cases such as class instances can be ignored when dealing with location and keyword parameters

More flexible: after conditional judgment on instance values, it is easier to make the decorator universal

Thank you for reading this article carefully. I hope the article "python how to write a flatter decorator using wrapt module" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report