python-decorators

How to use decorator in observer pattern for Python 2.7

Deadly 提交于 2019-12-10 17:33:21
问题 The observer pattern in the very simplified code below works well. I would like to have have a decorator @on_event that does the registration in the Observable singleton. In class O2 below this does not work. The problem is of course that the decorator on_event get's called prior to the instance is created, and the registration will be to the unbound method event . In some way I have to delay the registration until the O2 object is initialized. Maybe needless to say but all I want to add in

Python decorator to time recursive functions

旧巷老猫 提交于 2019-12-10 13:45:32
问题 I have a simple decorator to track the runtime of a function call: def timed(f): def caller(*args): start = time.time() res = f(*args) end = time.time() return res, end - start return caller This can be used as follows, and returns a tuple of the function result and the execution time. @timed def test(n): for _ in range(n): pass return 0 print(test(900)) # prints (0, 2.69e-05) Simple enough. But now I want to apply this to recursive functions. Applying the above wrapper to a recursive

Get route value from inside a decorator

别来无恙 提交于 2019-12-10 11:39:17
问题 In Flask, how do you get a route value (eg. '/admin') inside a decorator? I need to pass certain string to the DB depending on which route was used (and they all use the same decorator). @app.route('/admin') @decorator def admin(data): do_something(data) I couldn't find information about how to do it in Python. Is it possible? 回答1: You can define a new decorator which get the current route path then do something with it: from functools import wraps from flask import request def do_st_with

Why does inspect return different line for class inheriting from superclass?

安稳与你 提交于 2019-12-10 04:38:45
问题 While trying to figure out if a function is called with the @decorator syntax, we realized that inspect has a different behaviour when looking at a decorated class that inherits from a superclass. The following behaviour was found with CPython 3.6.2 under Windows 10. It was also reproduced in CPython 3.7.0 under Linux 64 bits. import inspect def decorate(f): lines = inspect.stack()[1].code_context print(f.__name__, lines) return f @decorate class Foo: pass @decorate class Bar(dict): pass

How do I return a value when @click.option is used to pass a command line argument to a function?

会有一股神秘感。 提交于 2019-12-10 02:59:02
问题 I am trying to use click python package to pass a command line argument to a function. The example from official documentation works as explained. But nowhere in the documentation is it mentioned how to return a value back. None of the functions in the documentation returns a value, so I don't understand how to do this. Given example at documentation: import click @click.command() @click.option('--count', default=3, help='Number of greetings.') def hello(count): """Simple program that greets

Changing a generator with another function - Python 3.x

吃可爱长大的小学妹 提交于 2019-12-08 13:36:54
问题 I want to change the behavior of the generator below so that it only yields even numbers. How can I do this? I'm aware that there simpler, clever ways to do this. This is a contrived HR challenge, where the The change_generator function that I wrote does not yield the desired output. I can only change change_generator . I cannot change positive_integers_generator() nor the for loop below. Can I solve this with a decorator? #can't change the body of this function def positive_integers

Attribute access on a decorated callable class

丶灬走出姿态 提交于 2019-12-08 05:15:54
问题 I have a callable class: class CallMeMaybe: __name__ = 'maybe' def __init__(self): self.n_calls = 0 def __call__(self): self.n_calls += 1 raise Exception That seems to work as advertised: >>> f = CallMeMaybe() >>> f.n_calls 0 >>> for i in range(7): ... try: ... f() ... except Exception: ... pass ... >>> f.n_calls 7 I want to decorate it with an exponential backoff: from backoff import on_exception, expo dec = on_exception(expo, Exception, max_tries=3, on_backoff=print) f = CallMeMaybe() f2 =

python setattr for dynamic method creator with decorator

大憨熊 提交于 2019-12-08 02:25:47
问题 I have a class which has multiple methods defined. import mat class Klass(object): @mat.sell(mat.CanSet): def method1(self): return None @mat.sell(mat.CanSet): def method2(self): return 'value2' Imagine I have 10 methods that I need to populate for this 'Klass'. I want to generate these methods without explicitely writing them all. So I want to do a factory that does setattr for each method. Problem is that I do following and the last method has the last value. Each do not get its related

Decorators for Instance Methods

非 Y 不嫁゛ 提交于 2019-12-08 02:01:17
问题 Wrapping a class's method in a "boilerplate" Python decorator will treat that method as a regular function and make it lose its __self__ attribute that refers to the class instance object. Can this be avoided? Take the following class: class MyClass(object): def __init__(self, a=1, b=2): self.a = a self.b = b def meth(self): pass If meth() is undecorated, MyClass().meth.__self__ refers to an instance method and enables something like setattr(my_class_object.meth.__self__, 'a', 5) . But when

Python: type checking decorator

眉间皱痕 提交于 2019-12-07 18:23:38
问题 I've built a type checking decorator (with wraps): def accepts_func(*types): """ top-level decoration, consumes parameters """ def decorator(func): """ actual decorator function, consumes the input function """ @wraps(func) def check_accepts(*args): """ actual wrapper which does some magic type-checking """ # check if length of args matches length of specified types assert len(args) == len(types), "{} arguments were passed to func '{}', but only {} " \ "types were passed to decorator '