How to Print the Name of a Variable in Python


One of the easiest ways to print the name of a variable in Python is by making use of the varname module.

Make sure to make use of the pip command to get it installed first.

pip install varname
Name: varname
Version: 0.11.2
Summary: Dark magics about variable names in python.
Home-page: https://github.com/pwwang/python-varname
Author: pwwang
Author-email: pwwang@pwwang.com
License: MIT
Location: /opt/homebrew/lib/python3.11/site-packages
Requires: executing
Required-by: 
Documentation:
Core features:

- Retrieving names of variables a function/class call is assigned to from inside it, using varname.
- Retrieving variable names directly, using nameof
- Detecting next immediate attribute name, using will
- Fetching argument names/sources passed to a function using argname
Reference: https://github.com/pwwang/python-varname
Usage Example:
from varname import nameof

name="Sam"
age=22
city="Chicago"

variable_name = nameof(name)
variable_age = nameof(age)
variable_city = nameof(city)

print(variable_name)
print(variable_age)
print(variable_city)
Print variable name in Python Example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap