Python decorating functions before call
I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?
Asked by: John263 | Posted: 27-01-2022
Answer 1
With:
decorator(original_function)()
Without:
original_function()
A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some documentation might help clarify things.
Answered by: Kellan445 | Posted: 28-02-2022Answer 2
def original_function():
pass
decorated_function= decorator(original_function)
if use_decorated:
decorated_function()
else:
original_function()
Decorate only once, and afterwards choose which version to call.
Answered by: Dainton745 | Posted: 28-02-2022Answer 3
Here is the recipe I came up with for the problem. I also needed to keep the signatures the same so I used the decorator module but you could re-jig to avoid that. Basically, the trick was to add an attribute to the function. The 'original' function is unbound so you need to pass in a 'self' as the first parameter so I added some extra code to check for that too.
# http://www.phyast.pitt.edu/~micheles/python/decorator-2.0.1.zip
from decorator import decorator, update_wrapper
class mustbe : pass
def wrapper ( interface_ ) :
print "inside hhh"
def call ( func, self, *args, **kwargs ) :
print "decorated"
print "calling %s.%s with args %s, %s" % (self, func.__name__, args, kwargs)
return interface_ ( self, *args, **kwargs )
def original ( instance , *args, **kwargs ) :
if not isinstance ( instance, mustbe ) :
raise TypeError, "Only use this decorator on children of mustbe"
return interface_ ( instance, *args, **kwargs )
call = decorator ( call, interface_ )
call.original = update_wrapper ( original, call )
return call
class CCC ( mustbe ):
var = "class var"
@wrapper
def foo ( self, param ) :
"""foo"""
print self.var, param
class SSS ( CCC ) :
@wrapper ( hidden_=True )
def bar ( self, a, b, c ) :
print a, b, c
if __name__ == "__main__" :
from inspect import getargspec
print ">>> i=CCC()"
i=CCC()
print ">>> i.var = 'parrot'"
i.var = 'parrot'
print ">>> i.foo.__doc__"
print i.foo.__doc__
print ">>> getargspec(i.foo)"
print getargspec(i.foo)
print ">>> i.foo(99)"
i.foo(99)
print ">>> i.foo.original.__doc__"
print i.foo.original.__doc__
print ">>> getargspec(i.foo.original)"
print getargspec(i.foo.original)
print ">>> i.foo.original(i,42)"
i.foo.original(i,42)
print ">>> j=SSS()"
j=SSS()
print ">>> j.bar(1,2,3)"
j.bar(1,2,3)
Answered by: Patrick249 | Posted: 28-02-2022
Similar questions
Class Decorator decorating method in python
This question already has answers here:
python - How create decorator in Django for decorating view
I have view:
@decorator
def func(request):
hello = "hello"
return render_to_responce("test.html", locals() )
and template test.html:
{{ hello }}
{{ username }}
I want to write decorator for func(request), which adds a variable, USERNAME, to the function and returns two parameters in the template. I tried to make it as follows:
python - Decorating an instance method and calling it from the decorator
I am using nose test generators feature to run the same test with different contexts. Since it requires the following boiler plate for each test:
class TestSample(TestBase):
def test_sample(self):
for context in contexts:
yield self.check_sample, context
def check_sample(self,...
python - Decorator class decorating a class method
I've got a decorator that I've implemented as a class:
class Cached(object):
def __init__(self, func):
self.cache = None
self.func = func
def __call__(self, *args, **kwargs):
if self.cache is None or (time.time() - self.cache[0] >= 1000):
res = self.f(*args, **kwargs)
self.cache = (time.time(), res)
else:
res = self.cache[...
decorator - Wrap every function or class method in a Python module by default without decorating every one
I have some code from which I want to get an email whenever it runs into an exception like this.
try:
f(**kwargs)
except Exception as e:
# email me the environment
I know that Python decorators can work for this, like:
@check_error
def f()
@check_error
def g()
What if I want every code in my module be wrapped by default? Like
def f()...
python - Decorating class methods - how to pass the instance to the decorator?
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__()'
...
decorator - Python / How decorating a method part of a class without modifying said class?
MAIN TROUBLE
As an example, say I would like to decorate split() method of str class
(the example is representative of what I try to do, except I would like to decorate agg method of pandas DataFrame class).
At least, I get the same error.
I prefer not to use @ nor to create a child of str class to keep th...
python - How to test if a decorator is decorating a method or a function?
I am just wondering for a decorator how can it know if a the function it is decorating is a method, a function, a static method, or a class method? What is the most robust way to distinguish these four different types inside a decorator?
Decorating a Python class with a decorator as a class
Need some help to implement/understand how decorators as a class work in Python. Most examples I've found are either decorating a class, but implementend as a function, or implemented as a class, but decorating a function. My goal is to create decorators implemented as classes and decorate classes.
To be more specific, I want to create a @Logger decorator and use it in some of my classes. What this deco...
decorator - How to create a class decorating another class using python
My goal is to implement a classic Decorator pattern (not functional @decorator, provided by python from the box). But I don't want to implement every method and attribute in decorator class. I want to make it in a more universal and elegant way.
My approach:
class AbstractDec...
python - Decorating a parent class method
I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but not in the parent class.
Essentially, I am trying to accomplish the following:
class foo(Object):
def meth1(self, val):
self.value = val
class bar(foo):
meth1 = classmethod(foo.meth1)
django - Decorating Instance Methods in Python
Here's the gist of what I'm trying to do. I have a list of objects, and I know they have an instance method that looks like:
def render(self, name, value, attrs)
# Renders a widget...
I want to (essentialy) decorate these functions at runtime, as I'm iterating over the list of objects. So that their render functions become this:
def render(self, name, value, attrs)
se...
python - Decorating a method
In my Python app, I'm using events to communicate between different plugins.
Now, instead of registering the methods to the events manually, I thought I might use decorators to do that for me.
I would like to have it look like this:
@events.listento('event.name')
def myClassMethod(self, event):
...
I have first tried to do it like this:
def listento(to):
def...
python - Decorating a class method after @property
I want to wrap every method of various objects except __init__ using a decorator.
class MyObject(object):
def method(self):
print "method called on %s" % str(self)
@property
def result(self):
return "Some derived property"
def my_decorator(func):
def _wrapped(*args, **kwargs):
print "Calling decorated function %s" % func
return func(*args, **kw...
python - Decorating a DBUS method
I'm trying to combine DBUS' asynchronous method calls with Twisted's Deferreds, but I'm encountering trouble in tweaking the usual DBUS service method decorator to do this.
To use the DBUS async callbacks approach, you'd do:
class Service(dbus.service.Object):
@dbus.service.method(INTERFACE, async_callbacks=('callback', 'errback'))
def Resources(self, callback, errback):
callback({'...
python - decorating recursive functions
I have a decorator that I wrote that will time a given function. It seems to work well with any function, except for recursive functions.
Decorator:
def tictoc(repeats=3, loops=1):
def t(func):
from functools import partial, wraps
import timeit
@wraps(func)
def timer(*args, **kargs):
elapsed = timeit.repeat(partial(func, *args, **kargs), repeat = repe...
Class Decorator decorating method in python
This question already has answers here:
python - Decorating a method - how to call the method in oo fashion instead of procedural fashion
Following up on an earlier thread my question is how can I take this expression: fn(self,*args, **kwargs and call it in oo fashion like this self.fn(...) here is my total program with the failing line commented out:
def formatHeader(fn):
def wrapped(*args, **kwargs):
print ...
python - How create decorator in Django for decorating view
I have view:
@decorator
def func(request):
hello = "hello"
return render_to_responce("test.html", locals() )
and template test.html:
{{ hello }}
{{ username }}
I want to write decorator for func(request), which adds a variable, USERNAME, to the function and returns two parameters in the template. I tried to make it as follows:
python - preserve argspec when decorating?
This question already has answers here:
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python