python-decorators

Self-referencing inside class definition

不问归期 提交于 2019-12-01 17:56:05
How do I reference class object inside class definition? Could you advice me how you would do it? Or more specifically how do you pass class object inside decorator of class method? Here is a simple example, I'm trying to pass second method I'm declaring to decorator of first one. def decorate(w): def _wrap(f): def _call(*args, **kwargs): return w(f(*args, **kwargs)) def _call return _wrap class A(): @dec(A.w) def f(): return 2 def w(f): return fr + 5 As expected exception is raised NameError: name 'A' is not defined As a result of my investigation i learned that globals() doesn't contain A

Is it possible to numpy.vectorize an instance method?

允我心安 提交于 2019-12-01 16:44:21
I've found that the numpy.vectorize allows one to convert 'ordinary' functions which expect a single number as input to a function which can also convert a list of inputs into a list in which the function has been mapped to each input. For example, the following tests pass: import numpy as np import pytest @np.vectorize def f(x): if x == 0: return 1 else: return 2 def test_1(): assert list(f([0, 1, 2])) == [1, 2, 2] def test_2(): assert f(0) == 1 if __name__ == "__main__": pytest.main([__file__]) However, I've not been able to get this to work for an instance method which makes use of an

Decorator error: NoneType object is not callable

≡放荡痞女 提交于 2019-12-01 12:42:00
I wrote a function decorator like this: def tsfunc(func): def wrappedFunc(): print '%s() called' % func.__name__ return func() return wrappedFunc() @tsfunc def foo(): pass foo() # to get it work, use foo instead of foo() foo() I got following error message: foo() called Traceback (most recent call last): File "decorator.py", line 11, in <module> foo() TypeError: 'NoneType' object is not callable I get it work by replacing "foo()" with "foo". but I still didn't get the result I expected: foo() called seems like the foo function is only called once. Please help me understand why this is

Combine two python decorators into one

旧时模样 提交于 2019-12-01 06:33:23
Here are two decorators I'd like to combine as they are pretty similar, the difference is how a not authenticated user is handled. I'd prefer to have one single decorator that I can call with an argument. # Authentication decorator for routes # Will redirect to the login page if not authenticated def requireAuthentication(fn): def decorator(**kwargs): # Is user logged on? if "user" in request.session: return fn(**kwargs) # No, redirect to login page else: redirect('/login?url={0}{1}'.format(request.path, ("?" + request.query_string if request.query_string else ''))) return decorator #

Python decorators count function call

风格不统一 提交于 2019-12-01 05:57:06
I'm refreshing my memory about some python features that I didn't get yet, I'm learning from this python tutorial and there's an example that I don't fully understand. It's about a decorator counting calls to a function, here's the code: def call_counter(func): def helper(x): helper.calls += 1 return func(x) helper.calls = 0 return helper @call_counter def succ(x): return x + 1 if __name__ == '__main__': print(succ.calls) for i in range(10): print(succ(i)) print(succ.calls) What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the

Combine two python decorators into one

泪湿孤枕 提交于 2019-12-01 05:23:40
问题 Here are two decorators I'd like to combine as they are pretty similar, the difference is how a not authenticated user is handled. I'd prefer to have one single decorator that I can call with an argument. # Authentication decorator for routes # Will redirect to the login page if not authenticated def requireAuthentication(fn): def decorator(**kwargs): # Is user logged on? if "user" in request.session: return fn(**kwargs) # No, redirect to login page else: redirect('/login?url={0}{1}'.format

setter method of property decorator not being called

拜拜、爱过 提交于 2019-12-01 03:57:43
I am trying to use a property method to set the status of a class instance, with the following class definition: class Result: def __init__(self,x=None,y=None): self.x = float(x) self.y = float(y) self._visible = False self._status = "You can't see me" @property def visible(self): return self._visible @visible.setter def visible(self,value): if value == True: if self.x is not None and self.y is not None: self._visible = True self._status = "You can see me!" else: self._visible = False raise ValueError("Can't show marker without x and y coordinates.") else: self._visible = False self._status =

Scope of variables in python decorator

纵饮孤独 提交于 2019-12-01 02:27:22
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: UnboundLocalError: local variable 'nr_of_rounds' referenced before assignment In other words, I can use nr

How to Make Decorators Optionally Turn On Or Off

拈花ヽ惹草 提交于 2019-11-30 16:43:34
I am asking, given a function with a decorator, is it possible to run the function without invoking the decorator call? Given a function foo , is it possible to optionally Turn On or Off a decorator on it? Given @decorator def foo(): //do_somthing Is it possible run foo with decorator Turned Off? There may exist some function where you may wish to run it with or without the decorator. For example(and not a good one, since it involves efficient caching) turn off decorator based caching in a factorial(n) function. My Question is Similar to this question Optionally use decorators on class methods

How to apply class decorator at base of all decorators on methods

ぃ、小莉子 提交于 2019-11-30 14:23:37
问题 I am using this way of decorating all methods import inspect def decallmethods(decorator, prefix='test_'): def dectheclass(cls): for name, m in inspect.getmembers(cls, inspect.ismethod): if name.startswith(prefix): setattr(cls, name, decorator(m)) return cls return dectheclass @decallmethods(login_testuser) class TestCase(object): def setUp(self): pass def test_1(self): print "test_1()" def test_2(self): print "test_2()" This is working but it applies at the top , if i have other decorators.