To have a function output its own name without a traceback module

Asked 2 years ago, Updated 2 years ago, 159 views

How do you get a function to output its own name without a traceback module?

For example, when the module foo has a bar function, in foo.bar() you would like to print bar is your name "bar" or "foo.bar".

What should I do now?

#foo.py  
def bar():
    print "my name is", __myname__ # How do I print this out?

function python traceback introspection

2022-09-22 11:50

1 Answers

There is no function in Python that determines its own name. It's been suggested before, but it's been rejected.

So if you want to print out your name,

def bar():
    print "my name is bar"

    #or
    print "my name is foo.bar"
def bar():
    print "my name is", bar.__name__
import inspect

def foo():
   print inspect.stack()[0][3]


2022-09-22 11:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.