python-decorators

Make @lru_cache ignore some of the function arguments

纵饮孤独 提交于 2019-11-27 02:06:50
问题 How can I make @functools.lru_cache decorator ignore some of the function arguments with regard to caching key? For example, I have a function that looks like this: def find_object(db_handle, query): # (omitted code) return result If I apply lru_cache decorator just like that, db_handle will be included in the cache key. As a result, if I try to call the function with the same query , but different db_handle , it will be executed again, which I'd like to avoid. I want lru_cache to consider

Decorator execution order

China☆狼群 提交于 2019-11-27 00:44:23
def make_bold(fn): return lambda : "<b>" + fn() + "</b>" def make_italic(fn): return lambda : "<i>" + fn() + "</i>" @make_bold @make_italic def hello(): return "hello world" helloHTML = hello() Output: "<b><i>hello world</i></b>" I roughly understand about decorators and how it works with one of it in most examples. In this example, there are 2 of it. From the output, it seems that @make_italic executes first, then @make_bold . Does this mean that for decorated functions, it will first run the function first then moving towards to the top for other decorators? Like @make_italic first then

How to use Python decorators to check function arguments?

与世无争的帅哥 提交于 2019-11-26 21:54:36
I would like to define some generic decorators to check arguments before calling some functions. Something like: @checkArguments(types = ['int', 'float']) def myFunction(thisVarIsAnInt, thisVarIsAFloat) ''' Here my code ''' pass Side notes: Type checking is just here to show an example I'm using Python 2.7 but Python 3.0 whould be interesting too From the Decorators for Functions and Methods : def accepts(*types): def check_accepts(f): assert len(types) == f.func_code.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ "arg %r does not match %s" %

Real world example about how to use property feature in python?

邮差的信 提交于 2019-11-26 19:24:49
I am interested in how to use @property in Python. I've read the python docs and the example there, in my opinion, is just a toy code: 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 I do not know what benefit(s) I can get from wrapping the _x filled with the property decorator. Why not just implement as: class C(object): def __init__(self): self.x = None I think, the property feature might be useful in some situations. But when? Could someone

How do I pass extra arguments to a Python decorator?

帅比萌擦擦* 提交于 2019-11-26 18:28:19
I have a decorator like below. def myDecorator(test_func): return callSomeWrapper(test_func) def callSomeWrapper(test_func): return test_func @myDecorator def someFunc(): print 'hello' I want to enhance this decorator to accept another argument like below def myDecorator(test_func,logIt): if logIt: print "Calling Function: " + test_func.__name__ return callSomeWrapper(test_func) @myDecorator(False) def someFunc(): print 'Hello' But this code gives the error, TypeError: myDecorator() takes exactly 2 arguments (1 given) Why is the function not automatically passed? How do I explicitly pass the

Python decorator, self is mixed up [duplicate]

≡放荡痞女 提交于 2019-11-26 16:42:49
问题 This question already has answers here : Decorating Python class methods - how do I pass the instance to the decorator? (4 answers) Closed 3 months ago . I am new to Python decorators (wow, great feature!), and I have trouble getting the following to work because the self argument gets sort of mixed up. #this is the decorator class cacher(object): def __init__(self, f): self.f = f self.cache = {} def __call__(self, *args): fname = self.f.__name__ if (fname not in self.cache): self.cache[fname

How to use Python decorators to check function arguments?

∥☆過路亽.° 提交于 2019-11-26 08:06:22
问题 I would like to define some generic decorators to check arguments before calling some functions. Something like: @checkArguments(types = [\'int\', \'float\']) def myFunction(thisVarIsAnInt, thisVarIsAFloat) \'\'\' Here my code \'\'\' pass Side notes: Type checking is just here to show an example I\'m using Python 2.7 but Python 3.0 whould be interesting too 回答1: From the Decorators for Functions and Methods: Python 2 def accepts(*types): def check_accepts(f): assert len(types) == f.func_code

How do I pass extra arguments to a Python decorator?

大憨熊 提交于 2019-11-26 06:18:03
问题 I have a decorator like below. def myDecorator(test_func): return callSomeWrapper(test_func) def callSomeWrapper(test_func): return test_func @myDecorator def someFunc(): print \'hello\' I want to enhance this decorator to accept another argument like below def myDecorator(test_func,logIt): if logIt: print \"Calling Function: \" + test_func.__name__ return callSomeWrapper(test_func) @myDecorator(False) def someFunc(): print \'Hello\' But this code gives the error, TypeError: myDecorator()

Decorating Python class methods - how do I pass the instance to the decorator?

落花浮王杯 提交于 2019-11-26 04:37:08
问题 This is Python 2.5, and it\'s GAE too, not that it matters. I have the following code. I\'m decorating the foo() method in bar, using the dec_check class as a decorator. class dec_check(object): def __init__(self, f): self.func = f def __call__(self): print \'In dec_check.__init__()\' self.func() class bar(object): @dec_check def foo(self): print \'In bar.foo()\' b = bar() b.foo() When executing this I was hoping to see: In dec_check.__init__() In bar.foo() But I\'m getting \" TypeError: foo(

How can I decorate an instance method with a decorator class?

一笑奈何 提交于 2019-11-26 03:36:00
问题 Consider this small example: import datetime as dt class Timed(object): def __init__(self, f): self.func = f def __call__(self, *args, **kwargs): start = dt.datetime.now() ret = self.func(*args, **kwargs) time = dt.datetime.now() - start ret[\"time\"] = time return ret class Test(object): def __init__(self): super(Test, self).__init__() @Timed def decorated(self, *args, **kwargs): print(self) print(args) print(kwargs) return dict() def call_deco(self): self.decorated(\"Hello\", world=\"World\