Answers for "how to get function name in python"

0

get function name python

# You can get any function's or class's name as a string with __name__.
# In fact, using just __name__ will return a module's name, or "__main__"
# if the file is the current running script
def this_is_my_name():
  pass

class MyName:
    def __init__(self) -> None:
        pass
    
    def __str__(self) -> str:
      	# this is just so we can get a more readable output
        return "MyName Object"

# as you can see later on, you can't get a variable's name the same way
named_variable = 231
named_instance = MyName()

list_of_stuff_w_names = [this_is_my_name, MyName, named_instance, named_variable]

print ("- Script running in", __name__)

for stuff_w_name in list_of_stuff_w_names:
    try:
        print ("-", f"{stuff_w_name.__name__ = }")
    except AttributeError:
        print ("-", stuff_w_name, "doesn't have a __name__!")
        
"""
OUTPUT:
- Script running in __main__
- stuff_w_name.__name__ = 'this_is_my_name'
- stuff_w_name.__name__ = 'MyName'
- MyName Object doesn't have a __name__!
- 231 doesn't have a __name__!
"""
Posted by: Guest on July-11-2021
0

how to get calling function in python

# Python code to demonstrate calling the 
#This example will help you to learn about funtion and function call 
#added by: vikalp chaubey
# function from another function 

def Square(X): 
	# computes the Square of the given number 
	# and return to the caller function 
	return (X * X) 

def SumofSquares(Array, n): 

	# Initialize variable Sum to 0. It stores the 
	# Total sum of squares of the array of elements 
	Sum = 0
	for i in range(n): 

		# Square of Array[i] element is stored in SquaredValue 
		SquaredValue = Square(Array[i]) 

		# Cummulative sum is stored in Sum variable 
		Sum += SquaredValue 
	return Sum

# Driver Function 
Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
n = len(Array) 

# Return value from the function 
# Sum of Squares is stored in Total 
Total = SumofSquares(Array, n) 
print("Sum of the Square of List of Numbers:", Total)
Posted by: Guest on September-15-2020
-1

python get function from string name

module = __import__('foo')
func = getattr(module, 'bar')
func()
Posted by: Guest on June-25-2020

Code answers related to "how to get function name in python"

Python Answers by Framework

Browse Popular Code Answers by Language