Print function name in python

Как получить имя функции в виде строки в Python?

должен выводить «my_function» . Доступна ли такая функция в Python? Если нет, какие-либо идеи о том, как реализовать get_function_name_as_string , в Python?

В следующий раз, пожалуйста, укажите вашу мотивацию в вопросе. В своей нынешней форме он, очевидно, сбивает людей с толку, и некоторые из них склонны считать, что вы будете вызывать дословно get_function_name_as_string(my_function) и ожидаете в результате «my_function» . Я предполагаю, что ваша мотивация — это общий код, который работает с функцией как первоклассным объектом и должен получить имя функции, переданной в качестве аргумента.

Мотивация вопроса не имеет отношения к техническому ответу. Прекратите использовать его как оправдание для насмешек, критики, интеллектуального позирования и избегания ответов.

Мотивация может помочь решить, будет ли задан правильный вопрос. В этом примере пользователь уже четко знает имя функции, поэтому использовать другую функцию для его возврата? Почему бы просто не сделать что-то столь же простое, как print(«my_function») ? Ответ на это в мотивации.

@Dannid, это скучный аргумент. Если OP запрашивает имя функции, это потому, что она инкапсулирована или понята способом, который должен быть выведен, например, для целей отладки. Ручная настройка в среде, где требуется такое требование, является ужасной практикой программирования. У вас может быть список функций для вызова, или вам может быть передана функция и вы хотите записать имя функции. И еще миллион причин, кроме просто для развлечения / изучения Python, которого, если хотите, уже достаточно.

Перечитывая мой комментарий, я не уверен, почему я перешел на сторону желания мотивации в ОП. Мотивация должна быть неактуальной. Похоже, я играл адвоката бедного дьявола. Я полагаю, что я чувствовал и не очень хорошо общался, потому что это помогает узнать, какова цель функции — вы отлаживаете? Написание шаблона функции? Создание динамических глобальных переменных? Это одноразовая или постоянная функция, которую вы будете часто использовать? В любом случае, я должен был согласиться с тем, что мотивация не имеет отношения к техническому ответу, хотя это может помочь решить, какой технический ответ лучше.

Источник

How to Get a Function Name as a String in Python?

In this python tutorial, we will learn how to get a function name as a string.

Table Of Contents

Get a function name as a string using __name__

Python3 version supports this method which is used to get the function name in string format. It also returns the module name.

Читайте также:  Nginx 404 index html

Here, the function is the function name. If you want to check the type of the returned function, then you can use the type() function. It returns the string class type.

Frequently Asked:

In this example, we will create two functions and get the function names and their types using __name__ .

# Create a function named my_first_function. def my_first_function(): print ("This is my first function") # Call the function my_first_function() # Get the function name as string print ("Function name: ", my_first_function.__name__) # Get the type print ("Function type: ", type(my_first_function.__name__)) # Create a function named my_second_function. def my_second_function(): print ("This is my second function") # Call the function my_second_function() # Get the function name as a string print ("Function name: ", my_second_function.__name__) # Get the type print ("Function type: ", type(my_second_function.__name__))

This is my first function Function name: my_first_function Function type: This is my second function Function name: my_second_function Function type:

You can see that the function name is returned and the type is str, which represents the string.

In this example, we imported two modules and get the module name and its type using name .

import math import random # Get the math module name as string print ("Function name: ", math.__name__) # Get the type of math print ("Function type: ", type(math.__name__)) # Get the random module name as string print ("Function name: ", random.__name__) # Get the type of random print ("Function type: ", type(random.__name__))

Function name: math Function type: Function name: random Function type:

You can see that the module name is returned and the type is str, which represents the string.

Get a function name as a string using func_name

Python2 version supports this method which is used to get the function name in string format. It is deprecated in the python3 version.

Here, the function is the function name. If you want to check the type of the returned function, then you can use the type() function. It returns the class type.

In this example, we will create two functions and get the function names and their types using func_name.

# Create a function named my_first_function. def my_first_function(): print ("This is my first function") # Call the function my_first_function() # Get the function name as string print ("Function name: ", my_first_function.func_name) # Get the type print ("Function type: ", type(my_first_function.func_name)) # Create a function named my_second_function. def my_second_function(): print ("This is my second function") # Call the function my_second_function() # Get the function name as a string print ("Function name: ", my_second_function.func_name) # Get the type print ("Function type: ", type(my_second_function.func_name))
This is my first function ('Function name: ', 'my_first_function') ('Function type: ', ) This is my second function ('Function name: ', 'my_second_function') ('Function type: ', )

You can see that the function name is returned and the type is str, which represents the string. This code will not work with python3, it will work with previous versions of Python.

Читайте также:  Работа со своим классом java

Get a function name as a string using qualname

Python3 supports this method which is used to get the function name in string format. It also returns the names of the classes and methods.

Here, the function is the function name. If you want to check the type of the returned function, then you can use the type() function. It returns the class type.

In this example, we will create two functions and get the function names and their types using qualname .

# Create a function named my_first_function. def my_first_function(): print ("This is my first function") # Call the function my_first_function() # Get the function name as string print ("Function name: ", my_first_function.__qualname__ ) # Get the type print ("Function type: ", type(my_first_function.__qualname__ )) # Create a function named my_second_function. def my_second_function(): print ("This is my second function") # Call the function my_second_function() # Get the function name as a string print ("Function name: ", my_second_function.__qualname__ ) # Get the type print ("Function type: ", type(my_second_function.__qualname__ ))

This is my first function Function name: my_first_function Function type: This is my second function Function name: my_second_function Function type:

You can see that the function name is returned and the type is str, which represents the string.

Example 2:
In this example, we will create a class and get the module name and its type using name .

# Define a class with a method - hello class My_class(): def hello(self): pass # Get the class name as a string print ("Class name: ", My_class.__qualname__ ) # Get the class type print ("Class type: ", type(My_class.__qualname__ )) # Get the method name as a string print ("Method name: ", My_class.hello.__qualname__ ) # Get the method type print ("Method type: ", type(My_class.hello.__qualname__ ))

Class name: My_class Class type: Method name: My_class.hello Method type:

In the above code, we created a class named My_class, and a method-hello is created inside it. using qualname, we returned the function name as a string.

Summary

In this tutorial, we discussed three ways to return a function name as a string in python. The func_name does not work in the python 3 versions. If you want to get the class name and methods names as strings, you can use qualname .

Источник

Get Function Name in Python

Get Function Name in Python

This tutorial will introduce how to get the function name in Python.

Use the __name__ Property to Get the Function Name in Python

In Python, every single function that is declared and imported in your project will have the __name__ property, which you can directly access from the function.

Читайте также:  Hikari datasource java это

To access the __name__ property, just put in the function name without the parentheses and use the property accessor .__name__ . It will then return the function name as a string.

The below example declares two functions, calls them, and prints out their function names.

def functionA():  print ("First function called!")  def functionB():  print ("\nSecond function called!")  functionA() print ("First function name: ", functionA.__name__)  functionB() print ("Second function name: ", functionB.__name__) 
First function called! First function name: functionA  Second function called! Second function name: functionB 

Note that this solution also works with the imported and pre-defined functions. Let’s try it out with the print() function itself and a function from an imported Python module os .

import os  print("Function name: ", print.__name__) print("Imported function name: ", os.system.__name__) 
Function name: print Imported function name: system 

In summary, getting the function name in Python can easily be done by using the function property __name__ , a string property containing the function name without the parentheses.

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.

Related Article — Python Function

Источник

Python How to get function name?

In this tutorial, we are going to learn how to get the function name in Python. Getting the name any function is a straightforward thing. We have two different ways for Python2 and Python3. Let’s see both of them.

Python2

Every function in Python2 has a property called func_name that gives you the name of the current function. Let’s see an example. Make sure you are using Python2 while executing the following example.

Example

# defining a function def testing_function(): """ This is a simple function for testing """ return None print("Function name is (Python2) '<>'".format(testing_function.func_name))

Output

If you execute the above program, then you will get the following result.

Function name is (Python2)'testing_function'

Python3¶

The function property func_name is deprecated in Python3. We will get the name of the using property __name__ of the function. Let’s see an example. Make sure you are using Python3 while running the following code.

Example

# defining a function def testing_function(): """ This is a simple function for testing """ return None print(f"Function name is (Python3) ''")

Output

If you execute the above program, then you will get the following result.

Function name is (Python3) 'testing_function'

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Источник

Оцените статью