- Как получить имя переменной в Python во время выполнения?
- 8 ответов
- Python вывести название переменной
- # Table of Contents
- # Print a variable’s name in Python
- # Print a variable’s name using globals()
- # Having multiple variables with the same value
- # Objects are stored at a different location in memory
- # Print a variable’s name using locals()
- # The globals() dictionary vs the locals() dictionary
- # Print a variable’s name by storing it in a dictionary
- # Additional Resources
- Re: python: название переменной в виде строки
- Re: python: название переменной в виде строки
- Re: python: название переменной в виде строки
- Re: python: название переменной в виде строки
- список переменных
Как получить имя переменной в Python во время выполнения?
Есть ли способ узнать во время выполнения имя переменной (из кода)? Или имена переменных, забытые во время компиляции (байт-код или нет)? например:
>>> vari = 15 >>> print vari.~~name~~() 'vari'
Да, хорошо, это было 3 года назад, и я не помню, почему этот вопрос имел смысл. Но вот! это чрезвычайно популярно, так что есть что-то об этом.
Вот пример использования: есть переменные foo, bar, baz, я хочу получить словарь точно так же, как <'foo': foo, 'bar': bar, 'baz': baz>. Конечно, я могу напечатать как то, что я только что сделал, но не очень лаконично. locals() , на мой взгляд, передают слишком много информации, не идеально. То, что я ожидаю, это функция вроде magic_func([foo,bar,baz]) которая возвращает magic_func([foo,bar,baz]) мне словарь'foo':>
8 ответов
здесь базовая (может быть, странная) функция, которая показывает имя своего аргумента. идея заключается в анализе кода и поиске вызовов функции (добавленной в методе init, это могло бы помочь найти имя экземпляра, хотя с более сложным анализом кода)
def display(var): import inspect, re callingframe = inspect.currentframe().f_back cntext = "".join(inspect.getframeinfo(callingframe, 5)[3]) #gets 5 lines m = re.search("display\s+\(\s+(\w+)\s+\)", cntext, re.MULTILINE) print m.group(1), type(var), var
обратите внимание: получение нескольких строк из вызывающего кода помогает в том случае, если вызов был разделен, как в приведенном ниже примере:
но приведет к неожиданному результату:
display(first_var) display(second_var)
Если у вас нет контроля над форматом вашего проекта, вы все равно можете улучшить код для обнаружения и управления различными ситуациями.
В целом я предполагаю, что статический анализ кода может дать более надежный результат, но я слишком ленив, чтобы проверить его сейчас
Python вывести название переменной
Last updated: Feb 21, 2023
Reading time · 6 min
# Table of Contents
# Print a variable’s name in Python
To print a variable’s name:
- Use a formatted string literal to get the variable’s name and value.
- Split the string on the equal sign and get the variable’s name.
- Use the print() function to print the variable’s name.
Copied!site = 'bobbyhadz.com' result = f'site=>' print(result) # 👉️ site='bobbyhadz.com' # ✅ print variable name using f-string variable_name = f'site=>'.split('=')[0] print(variable_name) # 👉️ 'site'
We used a formatted string literal to get a variable’s name as a string.
As shown in the code sample, the same approach can be used to print a variable’s name and value.
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Copied!var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>' print(result) # 👉️ bobbyhadz
Make sure to wrap expressions in curly braces — .
Formatted string literals also enable us to use the format specification mini-language in expression blocks.
Copied!site = 'bobbyhadz.com' result = f'site=>' print(result) # 👉️ site='bobbyhadz.com'
The equal sign after the variable is used for debugging and returns the variable’s name and its value.
The expression expands to:
- The text before the equal sign.
- An equal sign.
- The result of calling the repr() function with the evaluated expression.
To get only the variable name, we have to split the string on the equal sign and return the first list item.
Copied!site = 'bobbyhadz.com' variable_name = f'site=>'.split('=')[0] print(variable_name) # 👉️ 'site'
The str.split() method splits the string into a list of substrings using a delimiter.
Copied!site = 'bobbyhadz.com' result = f'site=>' print(result) # 👉️ site='bobbyhadz.com' print(result.split('=')) # 👉️ ['site', "'bobbyhadz.com'"]
The method takes the following 2 parameters:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done (optional) |
You can use the str.join() method if you need to join the variable’s name and value with a different separator.
Copied!website = 'bobbyhadz' result = ':'.join(f'website=>'.split('=')) print(result) # 👉️ website:'bobbyhadz'
The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
Alternatively, you can use the globals() function.
# Print a variable’s name using globals()
This is a three-step process:
- Use the globals() function to get a dictionary that implements the current module namespace.
- Iterate over the dictionary to get the matching variable’s name.
- Use the print() function to print the variable’s name.
Copied!def get_var_name(variable): globals_dict = globals() return [ var_name for var_name in globals_dict if globals_dict[var_name] is variable ] site = 'bobbyhadz.com' print(get_var_name(site)) # 👉️ ['site'] print(get_var_name(site)[0]) # 👉️ 'site'
You can tweak the function if you also need to get the value.
Copied!def get_variable_name_value(variable): globals_dict = globals() return [ f'var_name>=globals_dict[var_name]>' for var_name in globals_dict if globals_dict[var_name] is variable ] website = 'bobbyhadz.com' # 👇️ ['website=bobbyhadz.com'] print(get_variable_name_value(website)) # 👇️ website=bobbyhadz.com print(get_variable_name_value(website)[0])
The globals function returns a dictionary that implements the current module namespace.
Copied!site = 'bobbyhadz.com' globals_dict = globals() # , '__spec__': None, '__annotations__': <>, '__builtins__': , '__file__': '/home/borislav/Desktop/bobbyhadz_python/main.py', '__cached__': None, 'globals_dict': > print(globals_dict)
We used a list comprehension to iterate over the dictionary.
Copied!site = 'bobbyhadz.com' globals_dict = globals() result = [key for key in globals_dict] # ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'site', 'globals_dict'] print(result)
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we check if the identity of the provided variable matches the identity of the current dictionary value.
Copied!def get_var_name(variable): globals_dict = globals() return [var_name for var_name in globals_dict if globals_dict[var_name] is variable] site = 'bobbyhadz.com' print(get_var_name(site)) # 👉️ ['site'] print(get_var_name(site)[0]) # 👉️ 'site'
The matching variable names (keys in the dictionary) get returned as a list.
# Having multiple variables with the same value
If you have multiple variables with the same value, pointing to the same location in memory, the list would contain multiple variable names.
Copied!site = 'bobbyhadz.com' domain = 'bobbyhadz.com' def get_var_name(variable): globals_dict = globals() return [ var_name for var_name in globals_dict if globals_dict[var_name] is variable ] print(get_var_name(site)) # 👉️ ['site', 'domain']
There are 2 variables with the same value and they point to the same location in memory, so the list returns 2 variable names.
# Objects are stored at a different location in memory
If you pass non-primitive objects to the function, you’d get a list containing only one item because the objects are stored in different locations in memory.
Copied!class Employee(): pass alice = Employee() bobby = Employee() def get_var_name(variable): globals_dict = globals() return [ var_name for var_name in globals_dict if globals_dict[var_name] is variable ] print(get_var_name(alice)) # 👉️ ['alice']
The two class instances are stored in different locations in memory, so the get_var_name() function returns a list containing a single variable name.
# Print a variable’s name using locals()
You can also use the locals() dictionary to print a variable’s names.
Copied!site = 'bobbyhadz.com' print(locals().items()) variable_name = [ key for key, value in locals().items() if value == 'bobbyhadz.com' ] print(variable_name) # 👉️ ['site'] print(variable_name[0]) # 👉️ site
The locals() function returns a dictionary that contains the current scope’s local variables.
Copied!site = 'bobbyhadz.com' # , '__spec__': None, '__annotations__': <>, # '__builtins__': , '__file__': '/home/borislav/Desktop/bobbyhadz_python/main.py', '__cached__': None> print(locals())
We used a list comprehension to print the variable that has a value of bobbyhadz.com .
# The globals() dictionary vs the locals() dictionary
This approach is similar to using the globals() dictionary, however, the locals() function returns a dictionary that contains the current scope’s local variables, whereas the globals dictionary contains the current module’s namespace.
Here is an example that demonstrates the difference between the globals() and the locals() dictionaries.
Copied!global_site = 'bobbyhadz.com' def print_variable_name(): local_site = 'bobbyhadz.com' local_name = [ key for key, value in locals().items() if value == 'bobbyhadz.com' ] print(f'local_name local_name>') # ----------------------------------------------- globals_dict = globals() global_name = [ var_name for var_name in globals_dict if globals_dict[var_name] == 'bobbyhadz.com' ] print(f'global_name global_name>') # local_name ['local_site'] # global_name ['global_site'] print_variable_name()
The function uses the locals() and globals() dictionaries to print the name of the variable that has a value of bobbyhadz.com .
There is a variable with the specified value in the global and local scopes.
The locals() dictionary prints the name of the local variable, whereas the globals() dictionary prints the name of the global variable.
# Print a variable’s name by storing it in a dictionary
An alternative approach is to store the variable’s name as a value in a dictionary.
Copied!my_dict = 'bobbyhadz': 'site', 'python': 'language', > print(my_dict['bobbyhadz']) # 👉️ site print(my_dict['python']) # 👉️ language
The code sample stores the values of the variables as keys in the dictionary and the names of the variables as values.
Here is an easier way to visualize this.
Copied!site = 'bobbyhadz' language = 'python' # ---------------------------------- my_dict = 'bobbyhadz': 'site', 'python': 'language', > print(my_dict['bobbyhadz']) # 👉️ site print(my_dict['python']) # 👉️ language
The approach is similar to a reverse mapping.
By swapping the dictionary’s keys and values, we can access variable names by values.
You can define a reusable function to make it more intuitive.
Copied!def get_name(dictionary, value): return dictionary[value] my_dict = 'bobbyhadz': 'site', 'python': 'language', > print(get_name(my_dict, 'bobbyhadz')) # 👉️ site print(get_name(my_dict, 'python')) # 👉️ language
The function takes a dictionary and a value as parameters and returns the corresponding name.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Re: python: название переменной в виде строки
Имя имеет ссылка. На каждую переменную может быть несколько ссылок, поэтому нет однозначной связи между переменной и именем.
Re: python: название переменной в виде строки
А нельзя ли как-нибудь «выдрать» название переменной, например, из locals(); там оно хранится в виде строки (и как-то в эту строку транслируется). Получается, что по названию переменной можно определить её значение, а наоборот — нет?
Re: python: название переменной в виде строки
А зачем вам это нужно? Объясните задачу, может быть можно решить её по другому? > А нельзя ли как-нибудь "выдрать" название переменной, например, из locals(); locals() возвращает словарь, где ключи - имена переменных. Выдрать можно, например, так: for name,value in locals().items(): if value is x: print name Результат может быть не единственным, если на это значение есть несколько ссылок. Ну и эффективность, конечно же, не та.
Re: python: название переменной в виде строки
>А зачем вам это нужно? 1. Конкретная задача: есть список переменных, значения которых нужно отобразить в полях формы. Причём название поля = название переменной. 2. Интересно :) >может быть можно решить её по другому? да, конечно, на данный момент я делаю примерно так: for entry, value in (("x", x), ("y", y), ("z", z)): gui.get_widget (entry).set_text (value)
список переменных
> 1. Конкретная задача: есть список переменных, значения которых нужно отобразить в полях формы. Причём название поля = название переменной.
А зачем их делать отдельными переменными? Поместите их все в словарь.