for a function there is a name it is initially defined as in the def statement and the name it is called as in which would be different if the function reference is assigned to a different variable name and is called using that name. are there dunder names for these that would not have a value like '__main__' or None inside a function (or class method)? or maybe is there a way using module inspect?
There is
__name__
>>> def foo():
... pass
...
>>> dir(foo)
['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> foo.__name__
'foo'
>>> bar = foo
>>> bar.__name__
'foo'
that's outside of foo(). what about inside? code foo() to print() the value it has (e.g. for a function to realize its own name). the purpose is so i can insert or import some code from another file or module that will learn the name of the function it was in the definition of.
Output:
lt1a/forums/3 /home/forums 6> python3.8
Python 3.8.10 (default, Nov 22 2023, 10:22:35)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
... print(__name__)
...
>>> bar = foo
>>> bar()
__main__
>>>
lt1a/forums/3 /home/forums 7>
Use frames
>>> import sys
>>> def foo():
... print(sys._getframe().f_code.co_name)
...
>>> foo()
foo