How to run a method before / after all calls to class functions with arguments passed?

There are some interesting ways to run a method before each method in a class in questions such as Python: do something for any class method?

However, this solution does not allow us to pass arguments.

There is a decorator solution for Catch "before / after function call" events for all functions in the class , but I do not want to come back and decorate all my classes.

Is there a way to start the pre / post operation, which depends on the arguments passed for each call to the object's method?

Example:

class Stuff(object): def do_stuff(self, stuff): print(stuff) a = Stuff() a.do_stuff('foobar') "Pre operation for foobar" "foobar" "Post operation for foobar" 
+1
source share
1 answer

So, I realized this after a lot of experimentation.

Basically in the metaclass' __new__ you can iterate through each method in the class namespace and replace each method in the class created with the new version, which starts before the logic, the function itself and the logic after.Here is a sample:

 class TestMeta(type): def __new__(mcl, name, bases, nmspc): def replaced_fnc(fn): def new_test(*args, **kwargs): # do whatever for before function run result = fn(*args, **kwargs) # do whatever for after function run return result return new_test for i in nmspc: if callable(nmspc[i]): nmspc[i] = replaced_fnc(nmspc[i]) return (super(TestMeta, mcl).__new__(mcl, name, bases, nmspc)) 

Note that if you use this code the way it will trigger the pre / post operation for init and other built-in functions.

+2
source

Source: https://habr.com/ru/post/1203385/


All Articles