Skip to main content

How to Print Variable Names in Python

Printing a variable's name, rather than its value, is sometimes useful for debugging or introspection.

This guide explores several techniques to retrieve and display variable names in Python, ranging from using f-strings, to accessing the globals() and locals() dictionaries, and using a reverse-lookup dictionary.

Printing Variable Names with f-strings​

The most straightforward way to get a variable's name is using f-strings with the debugging feature.

site = 'tutorialreference.com'
result = f'{site=}'
print(result) # Output: site='tutorialreference.com'

variable_name = f'{site=}'.split('=')[0]
print(variable_name) # Output: site
  • The f-string f'{site=}' uses the debugging feature to print the variable’s name and value.
  • The .split('=')[0] extracts the variable's name by splitting the string by the equal sign and getting the string before it.

Printing Variable Names with globals()​

The globals() function returns a dictionary representing the current module's namespace, allowing you to get variable names.

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 = 'tutorialreference.com'
print(get_var_name(site)) # Output: ['site']
print(get_var_name(site)[0]) # Output: site

Explanation:

  • The code iterates through all of the keys of the dictionary returned by globals().
  • It keeps the key as a variable name if the variable at that key in globals() dictionary matches the passed-in variable using identity comparison (is).
  • The get_var_name function returns a list of variable names that refer to the passed in value.
  • The [0] is used to access the first variable name that matched.

You can also get the variable name and its value:

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 = 'tutorialreference.com'
print(get_variable_name_value(website)) # Output: ['website=tutorialreference.com']
print(get_variable_name_value(website)[0]) # Output: website=tutorialreference.com
  • The f'{var_name}={globals_dict[var_name]}' creates a string including both the variable name and value.

1. Handling Multiple Variables with the Same Value​

If multiple variables have the same value, all of their names will be returned:

site = 'tutorialreference.com'
domain = 'tutorialreference.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)) # Output: ['site', 'domain']

2. Object Identity and globals()​

For non-primitive objects, such as class instances, variables will be stored in different locations in memory, and the list of matching variable names will only contain one item:

class Employee():
pass
anna = Employee()
david = 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(anna)) # Output: ['anna']

Printing Variable Names with locals()​

The locals() function returns a dictionary representing the current local scope, allowing you to get the names of local variables.

site = 'tutorialreference.com'

variable_name = [
key for key, value in locals().items()
if value == 'tutorialreference.com'
]

print(variable_name) # Output: ['site']
print(variable_name[0]) # Output: site
  • The code iterates through the key value pairs from the dictionary returned by locals(), and returns the key if its value matches tutorialreference.com.

globals() vs locals()​

The locals() function gives the names in the current scope, whereas globals() returns the names in the module scope:

global_site = 'tutorialreferece.com'

def print_variable_name():
local_site = 'tutorialreferece.com'
local_name = [
key for key, value in locals().items()
if value == 'tutorialreferece.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] == 'tutorialreferece.com'
]

print(f'global_name {global_name}')
print_variable_name()

Output:

local_name ['local_site']
global_name ['global_site']

Printing Variable Names Using a Dictionary​

For a direct mapping between values and names, you can store them in a dictionary:

my_dict = {
'tutorialreference': 'site',
'python': 'language',
}
print(my_dict['tutorialreference']) # Output: site
print(my_dict['python']) # Output: language

You can also create a reusable function to do this:

def get_name(dictionary, value):
return dictionary[value]
my_dict = {
'tutorialreference': 'site',
'python': 'language',
}
print(get_name(my_dict, 'tutorialreference')) # Output: site
print(get_name(my_dict, 'python')) # Output: language

This approach lets you define a mapping from values to their corresponding variable names.