Essentially, I need to keep track of the methods that I wrap with this decorator to use later by editing the original object. The code works if I call the method, but if I don't, the code in the wrapper never executes. The wrapper is the only place where I receive the object where I can modify it. So, I need some other way to modify the object without calling a method that I'm decorating in it.
I've been trying so many different ways but I just can't get this to work.
import functools
def decorator3(**kwargs):
print(1)
def decorator(function):
print(2)
#functools.wraps(function)
def wrapper(self, *args):
print(3)
self.__test__ = "test worked"
function(self, *args)
return wrapper
return decorator
class Test:
def __init__(self):
self.a = "test"
#decorator3()
def test(self):
print(self.a)
t = Test()
#t.test()
print(t.__test__)
Your code parts execute in different times.
The outer decorator function, where you print "1", is called where you read #decorator3(). The result of calling this function, decorator, is then immediately applied to the decorated function (resp. method), where you read the "2".
In your case, the inner decorator replaces the method with a different function which calls the original method. Only if you call this, you reach "3".
So:
at 1, you don't know anything about your function.
at 2, you know your function, but not in which class it lives in.
at 3, you know your object, but only if your function is called.
You have to decide what exactly you want to do: according to your description, you want to flag the functions. That's what you perfectly can do in "2".
You say
I need to keep track of the methods that I decorate later on in the code. Basically, I decorate it to "flag" the method, and I have multiple classes with different methods that I need to flag. I will be calling decorator3 in other classes, so I don't see how putting the decorator in init will help. By editing the original class, I can later on put the method in a dictionary which I was hoping the decorator would do.
Maybe the following works:
import functools
def method_flagger(function):
function._flag = "flag"
return function
list_of_methods = []
def flag_reader(function):
#functools.wraps(function)
def wrapper(self, *args):
for i in dir(self.__class__):
#for i, j in self.__class__.__dict__.items():
method_wrapper = getattr(self, i)
if hasattr(getattr(self, i), "_flag"):
list_of_methods.append((self, i))
return function(self, *args)
return wrapper
class Test:
#flag_reader
def __init__(self):
self.a = "test"
#method_flagger
def test(self):
print(self.a)
#method_flagger
def test2(self):
print(self.a)
t1 = Test()
t2 = Test()
#t.test()
#print(t.__test__)
print(list_of_methods)
It gives me the output
[(<__main__.Test object at 0x000001D56A435860>, 'test'), (<__main__.Test object at 0x000001D56A435860>, 'test2'), (<__main__.Test object at 0x000001D56A435940>, 'test'), (<__main__.Test object at 0x000001D56A435940>, 'test2')]
so for each affected object instance and each decorated function, we get a tuple denoting these both.
Related
I was wondering if there was a way for a decorated function to refer to an object created by the wrapper of a decorator. My question arose when I was thinking to use a decorator to :
make a wrapper that creates a figure with subplots
inside the wrapper execute the decorated function which would add some plots
finally save the figure in the wrapper
However, the decorated function would need to refer the figure created by the wrapper. How can the decorated function refer to that object ? Do we necessarily have to resort to global variables ?
Here is a short example where I reference in the decorated function a variable created in the wrapper (but I did not manage to do this without tweaking with globals):
def my_decorator(func):
def my_decorator_wrapper(*args, **kwargs):
global x
x = 0
print("x in wrapper:", x)
return func(*args, **kwargs)
return my_decorator_wrapper
#my_decorator
def decorated_func():
global x
x += 1
print("x in decorated_func:", x)
decorated_func()
# prints:
# x in wrapper: 0
# x in decorated_func: 1
I know this would be easily done in a class, but I am asking this question out of curiosity.
Try to avoid using global variables.
Use arguments to pass objects to functions
There is one canonical way to pass a value to a function: arguments.
Pass the object as argument to the decorated function when the wrapper is called.
from functools import wraps
def decorator(f):
obj = 1
#wraps(f)
def wrapper(*args):
return f(obj, *args)
return wrapper
#decorator
def func(x)
print(x)
func() # prints 1
Use a default argument for passing the same object
If you need to pass the same object to all functions, storing it as default argument of your decorator is an alternative.
from functools import wraps
def decorator(f, obj={}):
#wraps(f)
def wrapper(*args):
return f(obj, *args)
return wrapper
#decorator
def func(params)
params['foo'] = True
#decorator
def gunc(params)
print(params)
func()
# proof that gunc receives the same object
gunc() # prints {'foo': True}
The above creates a common private dict which can only be accessed by decorated functions. Since a dict is mutable, changes will be reflected across function calls.
Yes, the function can refer to it by looking at itself.
the decorator end. it just takes attributes and sets them on the function
if it looks a bit complicated, that's because decorators that take parameters need this particular structure to work. see Decorators with parameters?
def declare_view(**kwds):
"""declaratively assocatiate a Django View function with resources
"""
def actual_decorator(func):
for k, v in kwds.items():
setattr(func, k, v)
return func
return actual_decorator
calling the decorator
#declare_view(
x=2
)
def decorated_func():
#the function can look at its own name, because the function exists
#by the time it gets called.
print("x in decorated_func:", decorated_func.x)
decorated_func()
output
x in decorated_func: 2
In practice I've used this quite a bit. The idea for me is to associate Django view functions with particular backend data classes and templates they have to collaborate with. Because it is declarative, I can introspect through all the Django views and track their associated URLs as well as custom data objects and templates. Works very well, but yes, the function does expect certain attributes to be existing on itself. It doesn't know that a decorator set them.
Oh, and there's no good reason, in my case, for these to be passed as parameters in my use cases, these variables hold basically hardcoded values which never change, from the POV of the function.
Odd at first, but quite powerful and no runtime or maintenance drawbacks.
Here's some live example that puts that in context.
#declare_view(
viewmanager_cls=backend.VueManagerDetailPSCLASSDEFN,
template_name="pssecurity/detail.html",
objecttype=constants.OBJECTTYPE_PERMISSION_LIST[0],
bundle_name="pssecurity/detail.psclassdefn",
)
def psclassdefn_detail(request, CLASSID, dbr=None, PORTAL_NAME="EMPLOYEE"):
"""
"""
f_view = psclassdefn_detail
viewmanager = f_view.viewmanager_cls(request, mdb, f_view=f_view)
...do things based on the parameters...
return viewmanager.HttpResponse(f_view.template_name)
Classes as Decorators
This article points to classes as decorators, which seems a more elegant way to point to the state defined in the decorator. It relies on function attributes and uses the special .__call__() method in the decorating class.
Here is my example revisited using a class instead of a function as a decorator:
class my_class_decorator:
def __init__(self, func):
self.func = func
self.x = 0
def __call__(self, *args, **kwargs):
print("x in wrapper:", self.x)
return self.func(*args, **kwargs)
#my_class_decorator
def decorated_func():
decorated_func.x += 1
print("x in decorated_func:", decorated_func.x)
decorated_func()
# prints:
# x in wrapper: 0
# x in decorated_func: 1
I am trying to detect whether a function is instance method or it is module level function inside the python decorator using the inspect.ismethod(). It returns false for that. what is the reason? How do I detect whether the function is instance method or the module level function inside the decorator like below.
Example:
import inspect
class A(object):
#deco("somearg")
def sample(self):
print "abc"
a = A()
print inspect.ismethod(a.sample) # Returns True
Above print returns true.
My decorator is something like below. I need to pass the arguments to decorator in the actual code so it's inside the function:
def deco(some_arg=None):
def decorator(func):
def wrapper(*args, **kwargs):
print some_arg
print inspect.ismethod(func)
return wrapper
return decorator
Above inspect.ismethod() returns false.
My python version is 2.7.13
Note that the transformation from function object to (unbound or
bound) method object happens each time the attribute is retrieved from
the class or instance.
What you're decorating is a function. And functions nested in classes are still functions. It classifies as a method when you access the function from the class or an instance of the class.
You can instead access the method object from the self parameter in your wrapper:
def deco(some_arg=None):
def decorator(func):
def wrapper(*args, **kwargs):
print some_arg
print inspect.ismethod(args[0].sample)
return wrapper
return decorator
I have been writing some functions for database operations in a script and decided to use a function decorator to handle the db connection boilerplate.
A stripped down example is shown below.
Function decorator:
import random
class funcdec(object):
def __init__(self,func):
self.state = random.random()
self.func = func
def __call__(self,*args,**kwargs):
return self.func(self.state,*args,**kwargs)
#funcdec
def function1(state,arg1,**kwargs):
print(state)
#funcdec
def function2(state,arg2,**kwargs):
print(state)
function1(10)
function2(20)
This means I can reduce the amount of boilerplate but I have a different state object per function. So if I run this I get something like:
python decf.py
0.0513280070328
0.372581711374
I wanted to implement a method for making this state shared by all the decorated functions and I came up with this.
Decorated Function decorator:
import random
class globaldec(object):
def __init__(self,func):
self.state = random.random()
def __call__(self,func,*args,**kwargs):
def wrapped(*args,**kawrgs):
return func(self.state,*args,**kwargs)
return wrapped
#globaldec
class funcdec(object):
pass
#funcdec
def function1(state,arg1,**kwargs):
print(state)
#funcdec
def function2(state,arg2,**kwargs):
print(state)
function1(10)
function2(20)
Now when I run this the state object is only created once per application and the state is the same for all decorated functions e.g.:
python decg.py
0.489779827086
0.489779827086
Intuitively this makes sense to me because the globaldec is only initialised once for all instances of the function decorator.
However, I am a little bit hazy on exactly what is going on here, and that fact that the funcdec object appears to not be initialised or called anymore.
Questions:
Does this technique have a name?
Can anyone shed some more light on what is going on internally?
You have created a decorator factory; a callable object that produces a decorator. In this case you are ignoring the func argument to globaldec.__init__() (the original funcdec class object) when using the globaldec class as a decorator. You instead replaced it with an instance of the globaldec class, which is then used as the real decorator for function1 and function2.
That's because decorators are just syntactic sugar; the #globaldec decorator applied to the class funcdec: line can be expressed like this:
class funcdec(object):
pass
funcdec = globaldec(funcdec)
so funcdec the class was replaced by an instance of globaldec instead.
Instead of using classes, I'd use functions; state like func and state become closures.
Your original decorator then can be written like this:
import random
def funcdec(func):
state = random.random()
def wrapper(*args, **kwargs):
return func(state, *args, **kwargs)
return wrapper
So when Python applies this as a decorator, funcdec() returns the wrapper function, replacing the original function1 or function2 functions are replaced by that function object. Calling wrapper() then in turn calls the original function object via the func closure.
The globaldec version just adds another layer; the outer function produces the decorator, moving the closure out one step:
import random
def globaldec():
state = random.random()
def funcdec(func):
def wrapper(*args, **kwargs):
return func(state, *args, **kwargs)
return wrapper
return funcdec
Just create the decorator once:
funcdec = globaldec()
#funcdec
def function1(state,arg1,**kwargs):
print(state)
#funcdec
def function2(state,arg2,**kwargs):
print(state)
An alternative pattern would be to store the state as a global (you could do so directly on the decorator function:
import random
def funcdec(func):
if not hasattr(funcdec, 'state'):
# an attribute on a global function is also 'global':
funcdec.state = random.random()
def wrapper(*args, **kwargs):
return func(funcdec.state, *args, **kwargs)
return wrapper
Now you no longer need to produce a dedicated decorator object, the wrapper now refers to funcdec.state as the shared value.
Here is what I want to do:
class demo(object):
def a(self):
pass
def b(self, param=self.a): #I tried demo.a as well after making a static
param()
The problem is apparently that one can't access the class in the function declaration line.
Is there a way to add a prototype like in c(++)?
At the moment I use a ugly workarround:
def b(self, param=True): #my real function shall be able to use None, to skip the function call
if param == True:
param = self.a
if param != None: #This explainds why I can't take None as default,
#for param, I jsut needed something as default which was
#neither none or a callable function (don't want to force the user to create dummy lambdas)
param()
So is it possible to achieve something like described in the top part without this ugly workarround? Note bene: I am bound to Jython which is approximately python 2.5 (I know there is 2.7 but I can't upgrade)
Short answer: No.
I think the best way to do it, if you want to be able to pass objects like None, True, etc., is to create a custom placeholder object like so:
default_value = object()
class demo(object):
def a(self):
pass
def b(self, param=default_value):
if param is default_value:
self.a()
else:
param()
You can use the funciton a as the default value for b, like so:
def b(self, param=a):
This will work long as a is defined before b. But the function a is not the same as the bound method self.a, so you'd need to bind it before you could call it, and you would need some way to distinguish a passed callable from the default method a, so that you could bind the latter but not the former. This would obviously be much messier than the comparatively short and readable code that I suggest.
Don't tell anyone I showed you this.
class demo:
def a(self): print(self, "called 'a'")
def b(self, param): param(self)
demo.b.__defaults__ = (demo.a,)
demo().b()
(In 2.x, __defaults__ is spelled func_defaults.)
I'll answer this question again, contradicting my earlier answer:
Short answer: YES! (sort of)
With the help of a method decorator, this is possible. The code is long and somewhat ugly, but the usage is short and simple.
The problem was that we can only use unbound methods as default arguments. Well, what if we create a wrapping function -- a decorator -- which binds the arguments before calling the real function?
First we create a helper class that can perform this task.
from inspect import getcallargs
from types import MethodType
from functools import wraps
class MethodBinder(object):
def __init__(self, function):
self.function = function
def set_defaults(self, args, kwargs):
kwargs = getcallargs(self.function, *args, **kwargs)
# This is the self of the method we wish to call
method_self = kwargs["self"]
# First we build a list of the functions that are bound to self
targets = set()
for attr_name in dir(method_self):
attr = getattr(method_self, attr_name)
# For older python versions, replace __func__ with im_func
if hasattr(attr, "__func__"):
targets.add(attr.__func__)
# Now we check whether any of the arguments are identical to the
# functions we found above. If so, we bind them to self.
ret = {}
for kw, val in kwargs.items():
if val in targets:
ret[kw] = MethodType(val, method_self)
else:
ret[kw] = val
return ret
So instances of MethodBinder are associated with a method (or rather a function that will become a method). MethodBinders method set_defaults may be given the arguments used to call the associated method, and it will bind any unbound method of the self of the associated method and return a kwargs dict that may be used to call the associated method.
Now we can create a decorator using this class:
def bind_args(f):
# f will be b in the below example
binder = MethodBinder(f)
#wraps(f)
def wrapper(*args, **kwargs):
# The wrapper function will get called instead of b, so args and kwargs
# contains b's arguments. Let's bind any unbound function arguments:
kwargs = binder.set_defaults(args, kwargs)
# All arguments have been turned into keyword arguments. Now we
# may call the real method with the modified arguments and return
# the result.
return f(**kwargs)
return wrapper
Now that we've put the uglyness behind us, let's show the simple and pretty usage:
class demo(object):
def a(self):
print("{0}.a called!".format(self))
#bind_args
def b(self, param=a):
param()
def other():
print("other called")
demo().b()
demo().b(other)
This recipe uses a rather new addition to python, getcallargs from inspect. It's available only in newer versions of python2.7 and 3.1.
You can put the method name in the function definition:
class Demo(object):
def a(self):
print 'a'
def b(self, param='a'):
if param:
getattr(self, param)()
However, you'll still have to check whether param has a value of whether it is None. Note that this approach should not be used for untrusted input as it allows execution of any function of that class.
I like lazyr's answer but maybe you will like this solution better:
class Demo(object):
def a(self):
pass
def b(self, *args):
if not args:
param=self.a
elif len(args)>1:
raise TypeError("b() takes at most 1 positional argument")
else:
param=args[0]
if param is not None:
param()
I also prefer lazyr's answer (I usually use None as the default parameter), but you can also use keyword arguments to be more explicit about it:
def b(self, **kwargs):
param = kwargs.get('param', self.a)
if param: param()
You can still use None as a parameter, resulting in param not being executed. However, if you don't include the keyword argument param=, it will default to a().
demo.b() #demo.a() executed
demo.b(param=some_func) #some_func() executed
demo.b(param=None) #nothing executed.
How to get all methods of a given class A that are decorated with the #decorator2?
class A():
def method_a(self):
pass
#decorator1
def method_b(self, b):
pass
#decorator2
def method_c(self, t=5):
pass
Method 1: Basic registering decorator
I already answered this question here: Calling functions by array index in Python =)
Method 2: Sourcecode parsing
If you do not have control over the class definition, which is one interpretation of what you'd like to suppose, this is impossible (without code-reading-reflection), since for example the decorator could be a no-op decorator (like in my linked example) that merely returns the function unmodified. (Nevertheless if you allow yourself to wrap/redefine the decorators, see Method 3: Converting decorators to be "self-aware", then you will find an elegant solution)
It is a terrible terrible hack, but you could use the inspect module to read the sourcecode itself, and parse it. This will not work in an interactive interpreter, because the inspect module will refuse to give sourcecode in interactive mode. However, below is a proof of concept.
#!/usr/bin/python3
import inspect
def deco(func):
return func
def deco2():
def wrapper(func):
pass
return wrapper
class Test(object):
#deco
def method(self):
pass
#deco2()
def method2(self):
pass
def methodsWithDecorator(cls, decoratorName):
sourcelines = inspect.getsourcelines(cls)[0]
for i,line in enumerate(sourcelines):
line = line.strip()
if line.split('(')[0].strip() == '#'+decoratorName: # leaving a bit out
nextLine = sourcelines[i+1]
name = nextLine.split('def')[1].split('(')[0].strip()
yield(name)
It works!:
>>> print(list( methodsWithDecorator(Test, 'deco') ))
['method']
Note that one has to pay attention to parsing and the python syntax, e.g. #deco and #deco(... are valid results, but #deco2 should not be returned if we merely ask for 'deco'. We notice that according to the official python syntax at http://docs.python.org/reference/compound_stmts.html decorators are as follows:
decorator ::= "#" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
We breathe a sigh of relief at not having to deal with cases like #(deco). But note that this still doesn't really help you if you have really really complicated decorators, such as #getDecorator(...), e.g.
def getDecorator():
return deco
Thus, this best-that-you-can-do strategy of parsing code cannot detect cases like this. Though if you are using this method, what you're really after is what is written on top of the method in the definition, which in this case is getDecorator.
According to the spec, it is also valid to have #foo1.bar2.baz3(...) as a decorator. You can extend this method to work with that. You might also be able to extend this method to return a <function object ...> rather than the function's name, with lots of effort. This method however is hackish and terrible.
Method 3: Converting decorators to be "self-aware"
If you do not have control over the decorator definition (which is another interpretation of what you'd like), then all these issues go away because you have control over how the decorator is applied. Thus, you can modify the decorator by wrapping it, to create your own decorator, and use that to decorate your functions. Let me say that yet again: you can make a decorator that decorates the decorator you have no control over, "enlightening" it, which in our case makes it do what it was doing before but also append a .decorator metadata property to the callable it returns, allowing you to keep track of "was this function decorated or not? let's check function.decorator!". And then you can iterate over the methods of the class, and just check to see if the decorator has the appropriate .decorator property! =) As demonstrated here:
def makeRegisteringDecorator(foreignDecorator):
"""
Returns a copy of foreignDecorator, which is identical in every
way(*), except also appends a .decorator property to the callable it
spits out.
"""
def newDecorator(func):
# Call to newDecorator(method)
# Exactly like old decorator, but output keeps track of what decorated it
R = foreignDecorator(func) # apply foreignDecorator, like call to foreignDecorator(method) would have done
R.decorator = newDecorator # keep track of decorator
#R.original = func # might as well keep track of everything!
return R
newDecorator.__name__ = foreignDecorator.__name__
newDecorator.__doc__ = foreignDecorator.__doc__
# (*)We can be somewhat "hygienic", but newDecorator still isn't signature-preserving, i.e. you will not be able to get a runtime list of parameters. For that, you need hackish libraries...but in this case, the only argument is func, so it's not a big issue
return newDecorator
Demonstration for #decorator:
deco = makeRegisteringDecorator(deco)
class Test2(object):
#deco
def method(self):
pass
#deco2()
def method2(self):
pass
def methodsWithDecorator(cls, decorator):
"""
Returns all methods in CLS with DECORATOR as the
outermost decorator.
DECORATOR must be a "registering decorator"; one
can make any decorator "registering" via the
makeRegisteringDecorator function.
"""
for maybeDecorated in cls.__dict__.values():
if hasattr(maybeDecorated, 'decorator'):
if maybeDecorated.decorator == decorator:
print(maybeDecorated)
yield maybeDecorated
It works!:
>>> print(list( methodsWithDecorator(Test2, deco) ))
[<function method at 0x7d62f8>]
However, a "registered decorator" must be the outermost decorator, otherwise the .decorator attribute annotation will be lost. For example in a train of
#decoOutermost
#deco
#decoInnermost
def func(): ...
you can only see metadata that decoOutermost exposes, unless we keep references to "more-inner" wrappers.
sidenote: the above method can also build up a .decorator that keeps track of the entire stack of applied decorators and input functions and decorator-factory arguments. =) For example if you consider the commented-out line R.original = func, it is feasible to use a method like this to keep track of all wrapper layers. This is personally what I'd do if I wrote a decorator library, because it allows for deep introspection.
There is also a difference between #foo and #bar(...). While they are both "decorator expressons" as defined in the spec, note that foo is a decorator, while bar(...) returns a dynamically-created decorator, which is then applied. Thus you'd need a separate function makeRegisteringDecoratorFactory, that is somewhat like makeRegisteringDecorator but even MORE META:
def makeRegisteringDecoratorFactory(foreignDecoratorFactory):
def newDecoratorFactory(*args, **kw):
oldGeneratedDecorator = foreignDecoratorFactory(*args, **kw)
def newGeneratedDecorator(func):
modifiedFunc = oldGeneratedDecorator(func)
modifiedFunc.decorator = newDecoratorFactory # keep track of decorator
return modifiedFunc
return newGeneratedDecorator
newDecoratorFactory.__name__ = foreignDecoratorFactory.__name__
newDecoratorFactory.__doc__ = foreignDecoratorFactory.__doc__
return newDecoratorFactory
Demonstration for #decorator(...):
def deco2():
def simpleDeco(func):
return func
return simpleDeco
deco2 = makeRegisteringDecoratorFactory(deco2)
print(deco2.__name__)
# RESULT: 'deco2'
#deco2()
def f():
pass
This generator-factory wrapper also works:
>>> print(f.decorator)
<function deco2 at 0x6a6408>
bonus Let's even try the following with Method #3:
def getDecorator(): # let's do some dispatching!
return deco
class Test3(object):
#getDecorator()
def method(self):
pass
#deco2()
def method2(self):
pass
Result:
>>> print(list( methodsWithDecorator(Test3, deco) ))
[<function method at 0x7d62f8>]
As you can see, unlike method2, #deco is correctly recognized even though it was never explicitly written in the class. Unlike method2, this will also work if the method is added at runtime (manually, via a metaclass, etc.) or inherited.
Be aware that you can also decorate a class, so if you "enlighten" a decorator that is used to both decorate methods and classes, and then write a class within the body of the class you want to analyze, then methodsWithDecorator will return decorated classes as well as decorated methods. One could consider this a feature, but you can easily write logic to ignore those by examining the argument to the decorator, i.e. .original, to achieve the desired semantics.
To expand upon #ninjagecko's excellent answer in Method 2: Source code parsing, you can use the ast module introduced in Python 2.6 to perform self-inspection as long as the inspect module has access to the source code.
def findDecorators(target):
import ast, inspect
res = {}
def visit_FunctionDef(node):
res[node.name] = [ast.dump(e) for e in node.decorator_list]
V = ast.NodeVisitor()
V.visit_FunctionDef = visit_FunctionDef
V.visit(compile(inspect.getsource(target), '?', 'exec', ast.PyCF_ONLY_AST))
return res
I added a slightly more complicated decorated method:
#x.y.decorator2
def method_d(self, t=5): pass
Results:
> findDecorators(A)
{'method_a': [],
'method_b': ["Name(id='decorator1', ctx=Load())"],
'method_c': ["Name(id='decorator2', ctx=Load())"],
'method_d': ["Attribute(value=Attribute(value=Name(id='x', ctx=Load()), attr='y', ctx=Load()), attr='decorator2', ctx=Load())"]}
If you do have control over the decorators, you can use decorator classes rather than functions:
class awesome(object):
def __init__(self, method):
self._method = method
def __call__(self, obj, *args, **kwargs):
return self._method(obj, *args, **kwargs)
#classmethod
def methods(cls, subject):
def g():
for name in dir(subject):
method = getattr(subject, name)
if isinstance(method, awesome):
yield name, method
return {name: method for name,method in g()}
class Robot(object):
#awesome
def think(self):
return 0
#awesome
def walk(self):
return 0
def irritate(self, other):
return 0
and if I call awesome.methods(Robot) it returns
{'think': <mymodule.awesome object at 0x000000000782EAC8>, 'walk': <mymodulel.awesome object at 0x000000000782EB00>}
For those of us who just want the absolute simplest possible case - namely, a single-file solution where we have total control over both the class we're working with and the decorator we're trying to track, I've got an answer. ninjagecko linked to a solution for when you have control over the decorator you want to track, but I personally found it to be complicated and really hard to understand, possibly because I've never worked with decorators until now. So, I've created the following example, with the goal of being as straightforward and simple as possible. It's a decorator, a class with several decorated methods, and code to retrieve+run all methods that have a specific decorator applied to them.
# our decorator
def cool(func, *args, **kwargs):
def decorated_func(*args, **kwargs):
print("cool pre-function decorator tasks here.")
return_value = func(*args, **kwargs)
print("cool post-function decorator tasks here.")
return return_value
# add is_cool property to function so that we can check for its existence later
decorated_func.is_cool = True
return decorated_func
# our class, in which we will use the decorator
class MyClass:
def __init__(self, name):
self.name = name
# this method isn't decorated with the cool decorator, so it won't show up
# when we retrieve all the cool methods
def do_something_boring(self, task):
print(f"{self.name} does {task}")
#cool
# thanks to *args and **kwargs, the decorator properly passes method parameters
def say_catchphrase(self, *args, catchphrase="I'm so cool you could cook an egg on me.", **kwargs):
print(f"{self.name} says \"{catchphrase}\"")
#cool
# the decorator also properly handles methods with return values
def explode(self, *args, **kwargs):
print(f"{self.name} explodes.")
return 4
def get_all_cool_methods(self):
"""Get all methods decorated with the "cool" decorator.
"""
cool_methods = {name: getattr(self, name)
# get all attributes, including methods, properties, and builtins
for name in dir(self)
# but we only want methods
if callable(getattr(self, name))
# and we don't need builtins
and not name.startswith("__")
# and we only want the cool methods
and hasattr(getattr(self, name), "is_cool")
}
return cool_methods
if __name__ == "__main__":
jeff = MyClass(name="Jeff")
cool_methods = jeff.get_all_cool_methods()
for method_name, cool_method in cool_methods.items():
print(f"{method_name}: {cool_method} ...")
# you can call the decorated methods you retrieved, just like normal,
# but you don't need to reference the actual instance to do so
return_value = cool_method()
print(f"return value = {return_value}\n")
Running the above example gives us the following output:
explode: <bound method cool.<locals>.decorated_func of <__main__.MyClass object at 0x00000220B3ACD430>> ...
cool pre-function decorator tasks here.
Jeff explodes.
cool post-function decorator tasks here.
return value = 4
say_catchphrase: <bound method cool.<locals>.decorated_func of <__main__.MyClass object at 0x00000220B3ACD430>> ...
cool pre-function decorator tasks here.
Jeff says "I'm so cool you could cook an egg on me."
cool post-function decorator tasks here.
return value = None
Note that the decorated methods in this example have different types of return values and different signatures, so the practical value of being able to retrieve and run them all is a bit dubious. However, in cases where there are many similar methods, all with the same signature and/or type of return value (like if you're writing a connector to retrieve unnormalized data from one database, normalize it, and insert it into a second, normalized database, and you have a bunch similar methods, e.g. 15 read_and_normalize_table_X methods), being able to retrieve (and run) them all on the fly could be more useful.
Maybe, if the decorators are not too complex (but I don't know if there is a less hacky way).
def decorator1(f):
def new_f():
print "Entering decorator1", f.__name__
f()
new_f.__name__ = f.__name__
return new_f
def decorator2(f):
def new_f():
print "Entering decorator2", f.__name__
f()
new_f.__name__ = f.__name__
return new_f
class A():
def method_a(self):
pass
#decorator1
def method_b(self, b):
pass
#decorator2
def method_c(self, t=5):
pass
print A.method_a.im_func.func_code.co_firstlineno
print A.method_b.im_func.func_code.co_firstlineno
print A.method_c.im_func.func_code.co_firstlineno
I don't want to add much, just a simple variation of ninjagecko's Method 2. It works wonders.
Same code, but using list comprehension instead of a generator, which is what I needed.
def methodsWithDecorator(cls, decoratorName):
sourcelines = inspect.getsourcelines(cls)[0]
return [ sourcelines[i+1].split('def')[1].split('(')[0].strip()
for i, line in enumerate(sourcelines)
if line.split('(')[0].strip() == '#'+decoratorName]
A simple way to solve this problem is to put code in the decorator that adds each function/method, that is passed in, to a data set (for example a list).
e.g.
def deco(foo):
functions.append(foo)
return foo
now every function with the deco decorator will be added to functions.