Is it possible to determine which class is a function?

For example, if I decorate such a method

def my_decorator(fn):

    # Do something based on the class that fn is a method of

    def decorated_fn(*args, **kwargs):
        fn(*args, **kwargs)

    return decorated_fn

class MyClass(object):

    @my_decorator
    def my_method(self, param):
        print "foo"

Is it possible in my_decorator to determine where fn came from?

+3
source share
2 answers

Short answer : None.

Longer answer . You can do this by retiring to the stack trace (see module inspect), but this is not a great idea.

Full answer . While the function is decorated, it is still an unrelated function. Try the following:

def my_dec(fn):
    print dir(fn) # Has "func_code" and "func_name"
    return fn

class A(object):
    @my_dec
    def test(self):
        pass

print dir(A.test) # Has "im_class" and "im_self"

You can see that the raw function is passed to the decorator, and the associated function is available after the class declaration.

, metaclass . , , .

+3

. , decorated_fn().

+1

Source: https://habr.com/ru/post/1770423/


All Articles