Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a function name dunder
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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'
« We can solve any problem by introducing an extra level of indirection »
Reply
#3
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>
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Use frames
>>> import sys
>>> def foo():
...     print(sys._getframe().f_code.co_name)
... 
>>> foo()
foo
Skaperen likes this post
« We can solve any problem by introducing an extra level of indirection »
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dunder Methods menator01 8 2,090 Mar-24-2022, 03:58 AM
Last Post: deanhystad
  Hi, looking for "dunder" tutorials. AlluminumFoil 3 2,156 Mar-02-2020, 08:37 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020