python-decorators

Decorators with arguments [duplicate]

拟墨画扇 提交于 2019-12-07 15:07:09
问题 This question already has answers here : Decorators with parameters? (10 answers) Closed 4 years ago . Code as follows def my_dec(func): def wrap(w): t = func(w) return t * 4 return wrap @my_dec def testing(n): return n new = testing(3) print(new) # This prints 12 This example is working fine, but now I'm trying to add the following to the decorator @my_dec(100) , I need to multiply the given number by 100. When I try this @my_dec(100) def testing(n): return n I get the following error:

How can I send unknown list of arguments to a python decorator?

∥☆過路亽.° 提交于 2019-12-07 11:55:14
问题 I have created a python decorator as shown below. I want this decorator to accept an unknown list of arguments. But the code below doesn't work. #!/usr/bin/env python from functools import wraps def my_decorator(decorated_function, **kwargs): print "kwargs = {}".format(kwargs) @wraps(decorated_function) def inner_function(*args, **kwargs): print "Hello world" return decorated_function(*args, **kwargs) return inner_function @my_decorator(arg_1="Yolo", arg2="Bolo") def my_func(): print "Woo Hoo

How to pass a class variable to a decorator inside class definition?

核能气质少年 提交于 2019-12-07 04:59:15
问题 I'd like to use a decorator which accepts an argument, checks if that argument is not None, and if True it lets the decorated function run. I want to use this decorator inside a class definition, because I have a set of class methods which starts with checking if a specific class variable is None or not. I think it would look nicer if I used a decorator. I'd like to do something like this: # decorator def variable_tester(arg): def wrap(f): def wrapped_f(*args): if arg is not None: f(*args)

How to design an async pipeline pattern in python

自作多情 提交于 2019-12-07 03:32:33
问题 I am trying to design an async pipeline that can easily make a data processing pipeline. The pipeline is composed of several functions. Input data goes in at one end of the pipeline and comes out at the other end. I want to design the pipeline in a way that: Additional functions can be insert in the pipeline Functions already in the pipeline can be popped out. Here is what I came up with: import asyncio @asyncio.coroutine def add(x): return x + 1 @asyncio.coroutine def prod(x): return x * 2

Nesting descriptors/decorators in python

不羁的心 提交于 2019-12-07 03:13:37
问题 I'm having a hard time understanding what happens when I try to nest descriptors/decorators. I'm using python 2.7. For example, let's take the following simplified versions of property and classmethod : class MyProperty(object): def __init__(self, fget): self.fget = fget def __get__(self, obj, objtype=None): print 'IN MyProperty.__get__' return self.fget(obj) class MyClassMethod(object): def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): print 'IN MyClassMethod.__get__'

Python set docstring and get method name of dynamically generated classmethod

安稳与你 提交于 2019-12-06 20:35:28
I'm trying to get/set the name and docstring of dynamically created class methods as follows, but am having trouble figuring out exactly how to do it: import sys import inspect class test(object): pass @classmethod def genericFunc(cls, **kwargs): print "function:", (inspect.stack()[0][3]) print "kwargs:", kwargs function_list = ['myF1', 'myF2'] for func in function_list: setattr(test, func, genericFunc) #set docstring for func here? if __name__ == '__main__': x = test() print "docstring:", x.myF1.__doc__ x.myF1(arg1="foo") y = test() print "docstring:", y.myF2.__doc__ y.myF2(arg1="foo", arg2=

Jython @property SyntaxError: mismatched input '' expecting CLASS

牧云@^-^@ 提交于 2019-12-06 15:39:43
I tried to run this example from the docs in the Jython interpreter: http://www.jython.org/docs/library/functions.html class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x Just entering the first 4 lines (up to and including @property ) yields a SyntaxError: >>> class C(object): ... def __init__(self): ... self._x = None ... @property File "<stdin>", line 4 @property ^ SyntaxError: mismatched input '' expecting CLASS Update: I am on Jython 2.5.2

python setattr for dynamic method creator with decorator

谁说胖子不能爱 提交于 2019-12-06 13:21:40
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 value but value10. Also below solution does not implement the decorator, I have no idea how to do assign

What is the intended lifetime of a Python decorator?

本秂侑毒 提交于 2019-12-06 08:47:57
问题 My question revolves around the intended lifetime of an implemented Python decorator. From realpython.org it says: ''By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.'' To me, it seems like decorators quite frequently are used in examples online to temporarily modify or extend a python function, such as in the html formatting examples. Example : Let's say that I work at a web development

How do I use the python-decorator package to decorate classmethods?

别来无恙 提交于 2019-12-06 08:44:25
问题 I'm have a decorator that I want to use to decorate class methods. In the following example, the @mydec decorator works fine on its own, however it does not preserve the function signature when using help() or pydoc. In order to fix this, I looked at using @decorator python-decorator package: import functools import decorator @decorator.decorator def mydec(func): @functools.wraps(func) def inner(cls, *args, **kwargs): # do some stuff return func(cls, *args, **kwargs) return inner class Foo