0

Is there better way to get function name inside the class.

I would like to get and <str> "A.boo" without using self.boo statement.

this is the test.py which I ran

import sys
import traceback

def foo():
    print(foo.__name__)
    print(foo.__qualname__)
    print(sys._getframe().f_code.co_name)
    print(traceback.extract_stack()[-2])


foo()

class A:
    def boo(self):
        print(self.boo.__name__)
        print(self.boo.__qualname__)
        print(sys._getframe().f_code.co_name)
        print(traceback.extract_stack()[-2])

A().boo()

output:

$ python test.py
foo
foo
foo
<FrameSummary file test.py, line 12 in <module>>
boo
A.boo
boo
<FrameSummary file test.py, line 21 in <module>>

1 Answer 1

1
import inspect


class A:
    def boo(self):
        print(self.__class__.__name__, end=“.”)
        print(inspect.currentframe().f_code.co_name)

Another way:

from decorator import decorator

@decorator
def prints_merhod_name(method, *args, **kwargs):
    self = args[0]
    print(self.__class__.__name__, method.__name__, sep=“.”)
    return method(*args, **kwargs)


class A:
    @prints_method_name
    def foo(self):
    whatever
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.