Как получить имя функции python
Перейти к содержимому

Как получить имя функции python

  • автор:

Name of a Python function

Vadim Pushtaev

In Python there are three things that can be considered being name of the function:

The original name of the code block

It’s stored in the f.__code__.co_name (where f is the function object). If you use def orig_name to create function, orig_name is that name. For lambas it's <lambda> .

This attribute is readonly and can’t be changed. So the only way to create function with the custom name in runtime I’m aware of is exec :

(There is also more low-level way to do this that.)

The immutability of co_name actually makes sense: with that you can be sure that the name you see in the debugger (or just stack trace) is exactly the same you see in the source code (along with the filename and line number).

The __name__ attribute of the function object

It’s also aliased to func_name .

You can modify it ( orig_name.__name__ = 'updated name' ) and you surely do on a daily basis: @functools.wraps copies the __name__ of the decorated function to the new one.

__name__ is used by tools like pydoc , that's why you need @functools.wraps : so you don't see the technical details of every decorator in your documentation. Look at the example:

Here is the pydoc output:

With wraps there is no sign of decorated in the documentation.

Name of the reference

One more thing that can be called function name (though it hardly is) is the name of a variable or an attribute where reference to that function is stored.

If you create function with def name , the name attribute will be added to the current scope. lambda , on the other hand, just returns a new value (which also can be assigned to attribute or variable: name = lambda: None `).

Obviously you can create more than one reference to the same function and all that references can have different names.

The only way all that three things are connected to each other is the
def foo statement that creates function object with both __name__ and __code__.co_name equal to foo and assign it to the foo attribute of the current scope. But they are not bound in any way and can be different from each other:

This article was originally posted as an answer to my own Stack Overflow question. I thank other people for comments and answers, they helped me to organize my thoughts and knowledge.

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

В Python, как мне получить имя функции как строку, не вызывая функцию?

должен выводить «my_function» .

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

9 ответов

Использование __name__ является предпочтительным методом, поскольку оно применяется равномерно. В отличие от func_name , он также работает со встроенными функциями:

Также двойные подчеркивания указывают читателю, что это особый атрибут. В качестве бонуса классы и модули имеют атрибут __name__ , поэтому вы помните только одно специальное имя.

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

Состав задачи, заданный объект функции, назначенного имени. Как получить имя функции как строку? Например, рассмотрим следующую функцию your_function. Как получить название «your_function» от этого? def your_function (): пройти string_name = . Ваше желаемое значение результата, хранящегося в String_Name, является строкой «your_function». … Как получить имя функции как строку в Python? Подробнее “

  • Автор записи

Автор оригинала: Chris.

Постановка проблемы

Учитывая функциональный объект, назначенный на имя. Как получить имя функции как строку?

Например, рассмотрим следующую функцию your_function Отказ Как получить имя «your_function» из этого?

Ваше желаемое значение результата хранится в string_name это строка «your_function» Отказ

Метод 1: Используйте атрибут __name__

Самый питонический способ извлечения имени от любого объекта или класса – использовать его __name__ атрибут. Атрибуты, заключенные в двойной подчеркивании (атрибуты Dunder), предоставляют специальные функциональные возможности для программистов Python. Например, звонок your_function .__ Имя__ дает строковое значение ‘your_function’ Отказ

Тем не менее, есть важный случай, когда этот метод потерпит неудачу.

�� Внимание : В Python функции являются объектами. Вы можете создавать несколько переменных, указывающих на тот же объект в памяти. Поэтому вы можете создать два имени func_1 и func_2 Это оба указывают на один и тот же объект функции. При звонке func_1 .__ name__ Результат может быть func_2 вместо func_1 что ты ожидал.

Это демонстрируется в следующем минимальном примере:

Как оба имена указывают на тот же объект памяти, но func_2 Во-первых, указывал на это имя объекта func_2 Отказ Использование памяти этого кода визуализируется с помощью инструмента Python Reputor:

Обе переменные относятся к тому же объекту функции, которые по умолчанию как func_2 имя.

Метод 2: Используйте атрибут __qualname__

Чтобы извлечь имя из любого объекта или класса, вы также можете использовать его __qualname__ атрибут. Например, звонок your_function .__ Qualname__ дает строковое значение ‘your_function’ Отказ Вы бы использовали __qualname__ над __имя__ Если вам также понадобится какой-то контекст, такой как класс, определяющий метод.

Следующий код создает функцию и способ внутри класса. Затем он сравнивает вывод __name__ и __qualname__ Атрибуты как функции, так и класса:

Вы можете погрузиться глубже в идиосинкразиях __qualname__ здесь и здесь Отказ

Спасибо за прочтение этой статьи. Чтобы повысить свои навыки Python, подумайте о том, чтобы присоединиться к бесплатной академии электронной почты Finxter с большим количеством чит-листов, учебников Python и забиты забавных программиров! ��

Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.

Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.

Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.

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.

Syntax:

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:

Syntax:

Example 1

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

Output:

Latest Python — Video Tutorial

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

Example 2:

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

Output:

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.

Syntax:

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.

Syntax:

Example:

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

Output:

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.

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.

Syntax:

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.

Syntax:

Example 1

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

Output:

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 .

Output:

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 .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *