Print a variable's name and value in Python

avatar

Borislav Hadzhiev

Last updated: Sep 8, 2022

banner

Photo from Unsplash

Print a variable's name and value in Python #

Use a formatted string literal to print a variable's name and value, e.g. print(f'{variable=}'). You can use an expression in f-strings to get a string that contains the variable's name and value.

main.py
name = 'bobbyhadz' result = f'{name=}' print(result) # 👉️ name='bobbyhadz' result = ':'.join(f'{name=}'.split('=')) print(result) # 👉️ name:'bobbyhadz'

We used a formatted string literal 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.
main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

main.py
website = 'bobbyhadz' result = f'{website=}' print(result) # 👉️ website='bobbyhadz'

The equal sign after the variable is used for debugging and returns the variable's name and its value.

The expression expands to:

  1. The text before the equal sign.
  2. An equal sign.
  3. The result of calling the repr() function with the evaluated expression.

You can use the split() function if you need to get only the name of the variable.

main.py
website = 'bobbyhadz' result = f'{website=}'.split('=')[0] print(result) # 👉️ 'website'

The str.split() method splits the string into a list of substrings using a delimiter.

main.py
website = 'bobbyhadz' result = f'{website=}' print(result) # 👉️ website='bobbyhadz' print(result.split()) # 👉️ ['website', "'bobbyhadz'"]

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt 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.

main.py
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.

The string the method is called on is used as the separator between the elements.

Alternatively, you can use the globals() function.

Print a variable's name and value using globals() #

To get a variable's name and value:

  1. Use the globals() function to get a dictionary that implements the current module namespace.
  2. Iterate over the dictionary to get the matching variable's name and value.
  3. Access the list item at index 0 to get the name and value of the variable.
main.py
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' print(get_variable_name_value(website)) # 👉️ ['website=bobbyhadz.com'] print(get_variable_name_value(website)[0]) # 👉️ website=bobbyhadz.com

The globals function returns a dictionary that implements the current module namespace.

main.py
website = 'bobbyhadz.com' globals_dict = globals() # {'website': 'bobbyhadz.com', '__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f1a57b19de0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__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.

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.

main.py
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' print(get_variable_name_value(website)) # 👉️ ['website=bobbyhadz.com'] print(get_variable_name_value(website)[0]) # 👉️ website=bobbyhadz.com

We used an f-string to return a string that contains the variable's name for the matching elements.

If you have multiple variables with the same value, pointing to the same location in memory, the list would contain multiple items.

main.py
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' name = 'bobbyhadz.com' # 👇️ ['website=bobbyhadz.com', 'name=bobbyhadz.com'] print(get_variable_name_value(website)) # 👇️ website=bobbyhadz.com print(get_variable_name_value(website)[0])
There are 2 variables with the same value, pointing to the same location in memory, so the list returns 2 items.

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.

main.py
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] class Employee(): pass alice = Employee() bobby = Employee() # 👇️ ['alice=<__main__.Employee object at 0x7f8faf25b4f0>'] print(get_variable_name_value(alice)) # 👇️ alice=<__main__.Employee object at 0x7f15de11f4f0> print(get_variable_name_value(alice)[0])

The two class instances are stored in different locations in memory, so the get_variable_name() function returns a list containing a single item.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.