python-decorators

Python: Use of decorators v/s mixins? [closed]

前提是你 提交于 2019-12-04 01:18:55
Closed . This question is opinion-based. It is not currently accepting answers. Learn more . Want to improve this question? Update the question so it can be answered with facts and citations by editing this post . Closed 4 years ago . I have understood the basics of decorators and mixins. Decorators add a new functionality to an object without changing other object instances of the same class, while a mixin is a kind of multiple inheritance used to inherit from multiple parent classes. Does it mean that decorators should be used when you'd need to modify only a single object instance and use

Scope of variables in python decorator

守給你的承諾、 提交于 2019-12-03 23:35:19
问题 I'm having a very weird problem in a Python 3 decorator. If I do this: def rounds(nr_of_rounds): def wrapper(func): @wraps(func) def inner(*args, **kwargs): return nr_of_rounds return inner return wrapper it works just fine. However, if I do this: def rounds(nr_of_rounds): def wrapper(func): @wraps(func) def inner(*args, **kwargs): lst = [] while nr_of_rounds > 0: lst.append(func(*args, **kwargs)) nr_of_rounds -= 1 return max(lst) return inner return wrapper I get: while nr_of_rounds > 0:

Having trouble making a custom django view decorator (with args)

╄→尐↘猪︶ㄣ 提交于 2019-12-03 20:44:16
So I've read all the similar questions and copied what they wrote but I still keep having issues. So I want something like this # Yes, I know django has one but I want to make my own @rate_limit(seconds=10) myview(request, somearg, *args, **kwargs): # Return a response ... def rate_limit(seconds=10): def decorator(view): def wrapper(request, *args, **kwargs): # Do some stuff return view(request, *args, **kwargs) return wrapper return decorator When I run it I get the error decorator() got an unexpected keyword argument 'somearg' So I append decorator to take in args and kwargs and get this

Wrapping all possible method calls of a class in a try/except block

自闭症网瘾萝莉.ら 提交于 2019-12-03 20:07:52
I'm trying to wrap all methods of an existing Class (not of my creation) into a try/except suite. It could be any Class, but I'll use the pandas.DataFrame class here as a practical example. So if the invoked method succeeds, we simply move on. But if it should generate an exception, it is appended to a list for later inspection/discovery (although the below example just issues a print statement for simplicity). (Note that the kinds of data-related exceptions that can occur when a method on the instance is invoked, isn't yet known; and that's the reason for this exercise: discovery). This post

Catch “before/after function call” events for all functions in class

非 Y 不嫁゛ 提交于 2019-12-03 19:17:19
问题 Is there any possibility to catch "before/after function call" events for all functions in class, without decorating each of these functions? May be some class decorator? In other words, for such code, I would like to get following output: class Foo: def func1(): print('1') def func2(): print('2') c = Foo() c.func1() c.func2() # Output I would like to get: # func1 called # 1 # func1 finished # func2 called # 2 # func2 finished I need it not for tracing. In class working with asynchronous

python decorator to display passed AND default kwargs

狂风中的少年 提交于 2019-12-03 15:35:40
I am new to python and decorators and am stumped in writing a decorator which reports not only passed args and kwargs but ALSO the unchanged default kwargs. This is what I have so far. def document_call(fn): def wrapper(*args, **kwargs): print 'function %s called with positional args %s and keyword args %s' % (fn.__name__, args, kwargs) return fn(*args, **kwargs) return wrapper @document_call def square(n, trial=True, output=False): # kwargs are a bit of nonsense to test function if not output: print 'no output' if trial: print n*n square(6) # with this call syntax, the default kwargs are not

Why do we need wrapper function in decorators?

别等时光非礼了梦想. 提交于 2019-12-03 13:38:15
If I create a decorator like following: def my_decorator(some_fun): def wrapper(): print("before some_function() is called.") some_fun() print("after some_function() is called.") return wrapper @my_decorator def just_some_function(): print("Wheee!") Another decorator can be defined as: def my_decorator(some_fun): print("before some_function() is called.") some_fun() print("after some_function() is called.") @my_decorator def just_some_fun(): print("some fun") Both decorators will work the same. What is the benefit of using "wrapper" function inside decorator. I didn't get the purpose. The

Function decorators with parameters on a class based view in Django

蹲街弑〆低调 提交于 2019-12-03 10:42:47
The official documentation explains how to decorate a class based view, however I could not find any information on how to provide parameters to the decorator. I would like to achieve something like class MyView(View): @method_decorator(mydecorator, some_parameters) def dispatch(self, *args, **kwargs): return super(MyView, self).dispatch(*args, **kwargs) which should be equivalent to @mydecorator(some_parameters) def my_view(request): .... How do I deal with such cases? @method_decorator takes a function as parameter. If you want to pass a decorator with parameters, you only need to: Evaluate

Python Decorator for printing every line executed by a function

两盒软妹~` 提交于 2019-12-03 08:20:01
问题 I want to, for debugging purposes, print out something pertaining to each and every line executed in a python method. For example if there was some assignment in the line, i want to print what value was assigned for that variable, and if there was a function call, i want to print out the value returned by the function, etc. So, for example if i were to use a decorator, applied on function/method such as : @some_decorator def testing() : a = 10 b = 20 c = a + b e = test_function() the function

Check if a function uses @classmethod

萝らか妹 提交于 2019-12-03 03:19:15
TL;DR How do I find out whether a function was defined using @classmethod or something with the same effect? My problem For implementing a class decorator I would like to check if a method takes the class as its first argument, for example as achieved via @classmethod def function(cls, ...): I found a solution to check for @staticmethod via the types module ( isinstance(foo, types.UnboundMethodType) is False if the foo is static, see here ), but did not find anything on how to do so for @classmethod Context What I am trying to do is something along the lines of def class_decorator(cls): for