I read this
one answer
and this
another answer
but I'm not doing it right with parameters
class decoratortest:
def dec(func):
def wrapper(self,*args,**kwargs):
func(*args,**kwargs)
func(*args,**kwargs)
return wrapper
#dec
def printer(self,a):
print(a)
def dectest(self):
self.printer('hi')
x = decoratortest()
x.dectest()
I get the usual positional error argument. What's the right syntax so I can print hi twice?
For the future, this worked:
class decoratortest:
def dec(func):
def wrapper(self,*args,**kwargs):
func(self,*args,**kwargs)
func(self,*args,**kwargs)
return wrapper
#dec
def printer(self,a):
print(a)
def dectest(self):
self.printer('hi')
x = decoratortest()
x.dectest()
very tricky, you dont' type self in the decorator, but you do in the underlying wrapper and func items.
You have to pass self explicitly, since func is a reference to a regular function object, not the method object that self.printer produces (via the descriptor protocol):
def dec(func):
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
func(self, *args, **kwargs)
return wrapper
Or you can put your decorator outside of the class
def dec(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
func(*args, **kwargs)
return wrapper
class decoratortest:
#dec
def printer(self, a):
print(a)
def dectest(self):
self.printer('hi')
x = decoratortest()
x.dectest()
Output:
hi
hi
class decoratortest:
def dec(func):
def wrapper(self,*args,**kwargs):
func(*args,**kwargs)
func(*args,**kwargs)
return wrapper
#dec
def printer(self,a='hi'):
print(a)
def dectest(self):
self.printer('hi')
x = decoratortest()
x.dectest()
Added a default value for decorator when argument is not specified and it worked.
Related
Trying to rewrite a decorator as a Class isn't working as expected. My actual decorator is:
def check(callback):
def decorator(function):
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
cb_result = callback()
return result
return wrapper
return decorator
My approach to class format is
class Check(object):
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
def __call__(self, *call_args, **call_kwargs):
function = call_args[0]
return self.__param__call__(function)
def __param__call__(self, function):
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
cb_result = callback()
return result
return wrapper
I expect to use the decorator as in:
#Check(callback=a_function_callback)
def my_function():
...
What is my mistake while rewriting it as a class, I'm also always trying to keep backwards compatibility (aka Python 2.7 compliance).
You should accept callback as a parameter in your Check class' __init__ method, so that your wrapper function can actually reference it as a callback function:
class Check(object):
def __init__(self, callback):
self.callback = callback
def __call__(self, func):
return self.__param__call__(func)
def __param__call__(self, func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
cb_result = self.callback()
return result
return wrapper
I want to call a wrapper method of function with argument just before I call specific method.
So I guess I have to ovewrite __getattribute__ method.
Here is an example of code:
def wrapper(func):
return func * 2
class A(object):
def test(self, arg):
return arg + 1
def __getattribute__(self, name):
if name in ['test']:
return wrapper(super(A, self).__getattribute__(name))
return super(A, self).__getattribute__(name)
The matter is that getattribute is called when test return the value. What I want is to be able to catch test with the arguments and define the wrapper method like this:
def wrapper(func, *args, **kwargs):
print "do some stuff"
return func(*args, **kwargs)
Use a factory function to return your wrapper:
def decorate(f):
def wrapper(*args, **kw):
return f(*args, **kw) * 2
return wrapper
Here f is closed over by wrapper(), so it can access the name when called.
Then return this in the __getattribute__ hook:
def __getattribute__(self, name):
result = super(A, self).__getattribute__(name)
if name in ('test',):
return decorate(result)
return result
Of course, you could also just apply decorate as a decorator on test then:
class A(object):
#decorate
def test(self, arg):
return arg + 1
If I understand you correctly, you can use a decorator.
def wrapper(func):
def _wrapper(*args, **kwargs):
return func(*args, **kwargs) * 2
return _wrapper
class A(object):
#wrapper
def test(self, arg):
return arg + 1
I have question about clean thory in Python. When:
#decorator_func
def func(bla, alba):
pass
Is equivalent to:
def func(bla, alba):
pass
func = decorator_func(func)
So:
#decorator_func(aaa, bar)
def func(bla, alba):
pass
Is equvalent to...?
It's equivalent to:
def func(bla, alba):
pass
func = decorator_func(aaa, bar)(func)
Or:
def func(bla, alba):
pass
decorator = decorator_func(aaa, bar)
func = decorator(func)
So in your second example, decorator_func should be a callable that returns a callable.
Here's an example of such a construction:
class prepend_two_arguments:
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self, f):
def wrapped_function(*args, **kwargs):
return f(self.a, self.b, *args, **kwargs)
return wrapped_function
#prepend_two_arguments(1,2)
def f(a, b, c):
return a+b+c
print(f(3)) # 6
And another one, using only functions:
def add_to_result(x):
def decorator(fn):
def wrapped_function(*args, **kwargs):
return fn(*args, **kwargs)+x
return wrapped_function
return decorator
#add_to_result(3)
def my_func(a, b):
return a+b
print(my_func(1,2)) # 6
Here's an example of a decorator function that works using closures:
def print_string_before(string):
def decorator_fn(fn):
def wrapped_fn(*args, **kwargs):
print string
return fn(*args, **kwargs)
return wrapped_fn
return decorator_fn
Note that decorators can equally return the decorated function (or class), having modified it in some way (e.g. setting an attribute).
I'm trying to write a decorator that works like #property, but running into some problems.
class Dec(object):
def __init__(self, fn):
self._fn = fn
self._before = None
#property
def before(self)
return self._before
#before.setter
def before(self, fn):
self._before = fn
def __call__(self, *args, **kwargs):
self._before(*args, **kwargs)
self._fn(*args, **kwargs)
def withbefore(fn):
return Dec(fn)
Its a simple chaining decorator. The #property/#.setter syntax is exactly what I'm trying to clone.
This works:
#withbefore
def foo():
...
#foo.before
def beforefoo():
...
But on a class it doesn't:
class Weee(object):
#withbefore
def do_stuff(self):
pass
#do_stuff.before
def before_do_stuff(self):
pass
It raises an import error.
TypeError: 'NoneType' object is not callable
How can i correctly emulate #property/.{setter,getter,deleter} ?
Actually, it raises a TypeError.
Anyway, I got the same error when running your decorator with functions, too. It happens because, when you decorate a function with #foo.before, it will call the self._before function with the decorated function as parameter. Since self._before is None, it will raise the error.
There are various solutions for it. My favorite is to set a different default value to self._before - a function which will set the self._before value:
class Dec(object):
def __init__(self, fn):
self._fn = fn
def setbefore(b):
self._before = b
self._before = self.default_before = setbefore
Of course, this function should not be called when the Dec object is called so we change the __call__ method:
def __call__(self, *args, **kwargs):
if self._before != self.default_before:
self._before(*args, **kwargs)
self._fn(*args, **kwargs)
Sincerely, I think you'd be better off with:
from functools import wraps
def withbefore(fn):
def dec(bef):
fn._before_fn = bef
return bef
#wraps(fn)
def _wrapper(*args, **kwargs):
fn._before_fn(*args, **kwargs)
return fn(*args, **kwargs)
_wrapper.before = dec
return _wrapper
It is more compact, more Pythonic and should work OK for all cases.
I have been trying to create a decorator that can be used with both functions and methods in python. This on it's own is not that hard, but when creating a decorator that takes arguments, it seems to be.
class methods(object):
def __init__(self, *_methods):
self.methods = _methods
def __call__(self, func):
def inner(request, *args, **kwargs):
print request
return func(request, *args, **kwargs)
return inner
def __get__(self, obj, type=None):
if obj is None:
return self
new_func = self.func.__get__(obj, type)
return self.__class__(new_func)
The above code wraps the function/method correctly, but in the case of a method, the request argument is the instance it is operating on, not the first non-self argument.
Is there a way to tell if the decorator is being applied to a function instead of a method, and deal accordingly?
To expand on the __get__ approach. This can be generalized into a decorator decorator.
class _MethodDecoratorAdaptor(object):
def __init__(self, decorator, func):
self.decorator = decorator
self.func = func
def __call__(self, *args, **kwargs):
return self.decorator(self.func)(*args, **kwargs)
def __get__(self, instance, owner):
return self.decorator(self.func.__get__(instance, owner))
def auto_adapt_to_methods(decorator):
"""Allows you to use the same decorator on methods and functions,
hiding the self argument from the decorator."""
def adapt(func):
return _MethodDecoratorAdaptor(decorator, func)
return adapt
In this way you can just make your decorator automatically adapt to the conditions it is used in.
def allowed(*allowed_methods):
#auto_adapt_to_methods
def wrapper(func):
def wrapped(request):
if request not in allowed_methods:
raise ValueError("Invalid method %s" % request)
return func(request)
return wrapped
return wrapper
Notice that the wrapper function is called on all function calls, so don't do anything expensive there.
Usage of the decorator:
class Foo(object):
#allowed('GET', 'POST')
def do(self, request):
print "Request %s on %s" % (request, self)
#allowed('GET')
def do(request):
print "Plain request %s" % request
Foo().do('GET') # Works
Foo().do('POST') # Raises
The decorator is always applied to a function object -- have the decorator print the type of its argument and you'll be able to confirm that; and it should generally return a function object, too (which is already a decorator with the proper __get__!-) although there are exceptions to the latter.
I.e, in the code:
class X(object):
#deco
def f(self): pass
deco(f) is called within the class body, and, while you're still there, f is a function, not an instance of a method type. (The method is manufactured and returned in f's __get__ when later f is accessed as an attribute of X or an instance thereof).
Maybe you can better explain one toy use you'd want for your decorator, so we can be of more help...?
Edit: this goes for decorators with arguments, too, i.e.
class X(object):
#deco(23)
def f(self): pass
then it's deco(23)(f) that's called in the class body, f is still a function object when passed as the argument to whatever callable deco(23) returns, and that callable should still return a function object (generally -- with exceptions;-).
Since you're already defining a __get__ to use your decorator on the Bound Method, you could pass a flag telling it if it's being used on a method or function.
class methods(object):
def __init__(self, *_methods, called_on_method=False):
self.methods = _methods
self.called_on_method
def __call__(self, func):
if self.called_on_method:
def inner(self, request, *args, **kwargs):
print request
return func(request, *args, **kwargs)
else:
def inner(request, *args, **kwargs):
print request
return func(request, *args, **kwargs)
return inner
def __get__(self, obj, type=None):
if obj is None:
return self
new_func = self.func.__get__(obj, type)
return self.__class__(new_func, called_on_method=True)
Here is a general way I found to detect whether a decorated callable is a function or method:
import functools
class decorator(object):
def __init__(self, func):
self._func = func
self._obj = None
self._wrapped = None
def __call__(self, *args, **kwargs):
if not self._wrapped:
if self._obj:
self._wrapped = self._wrap_method(self._func)
self._wrapped = functools.partial(self._wrapped, self._obj)
else:
self._wrapped = self._wrap_function(self._func)
return self._wrapped(*args, **kwargs)
def __get__(self, obj, type=None):
self._obj = obj
return self
def _wrap_method(self, method):
#functools.wraps(method)
def inner(self, *args, **kwargs):
print('Method called on {}:'.format(type(self).__name__))
return method(self, *args, **kwargs)
return inner
def _wrap_function(self, function):
#functools.wraps(function)
def inner(*args, **kwargs):
print('Function called:')
return function(*args, **kwargs)
return inner
Example usage:
class Foo(object):
#decorator
def foo(self, foo, bar):
print(foo, bar)
#decorator
def foo(foo, bar):
print(foo, bar)
foo(12, bar=42) # Function called: 12 42
foo(12, 42) # Function called: 12 42
obj = Foo()
obj.foo(12, bar=42) # Method called on Foo: 12 42
obj.foo(12, 42) # Method called on Foo: 12 42
A partial (specific) solution I have come up with relies on exception handling. I am attempting to create a decorator to only allow certain HttpRequest methods, but make it work with both functions that are views, and methods that are views.
So, this class will do what I want:
class methods(object):
def __init__(self, *_methods):
self.methods = _methods
def __call__(self, func):
#wraps(func)
def inner(*args, **kwargs):
try:
if args[0].method in self.methods:
return func(*args, **kwargs)
except AttributeError:
if args[1].method in self.methods:
return func(*args, **kwargs)
return HttpResponseMethodNotAllowed(self.methods)
return inner
Here are the two use cases: decorating a function:
#methods("GET")
def view_func(request, *args, **kwargs):
pass
and decorating methods of a class:
class ViewContainer(object):
# ...
#methods("GET", "PUT")
def object(self, request, pk, *args, **kwargs):
# stuff that needs a reference to self...
pass
Is there a better solution than to use exception handling?