Getting the name of a variable as a string
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python, variables are labels pointing to objects, not objects carrying their own canonical names. Because multiple variables can reference the same object, asking for the variable name at runtime is usually the wrong abstraction. Most robust solutions pass names explicitly or use structured data containers.
Why Python Does Not Guarantee One Variable Name
An object can be referenced by many names, or by no name at all.
If you ask for the object name here, should it be x or y. Python cannot provide a unique answer. This is why name lookup by object identity is unreliable.
Preferred Pattern: Pass the Name Explicitly
If you need a label for logs or diagnostics, pass it as data.
This is explicit, predictable, and easy to test.
Use Dictionaries for Name Value Pairs
When names are data, store them in a dictionary.
This usually matches business needs better than introspection hacks.
Introspection with locals or globals
You can search scope mappings for objects, but results are context dependent and ambiguous.
This may print multiple names and can change with refactoring. Treat it as debugging only, not production logic.
Structured Objects with Field Names
If the real need is identifying fields, use dataclasses or models where names are stable schema keys.
Field names like task_id are part of the model, so they are reliable and portable.
Logging and Diagnostics Without Variable Name Lookup
For diagnostics, structured logging is typically better than dynamic name discovery.
Here, key names are explicit and searchable in log systems.
When You Really Need Expression Text
Some test frameworks show expression text through assertion rewriting, but that is framework machinery, not normal Python runtime semantics. If you want similar behavior, capture message strings directly.
Passing a label string keeps intent clear and avoids brittle reflection.
Use Constants for Stable Keys
If repeated string labels feel error prone, define constants or enums for key names. This gives autocomplete support and prevents typographical mistakes while still keeping naming explicit instead of relying on runtime variable lookup tricks.
This approach also makes static analysis and refactoring tools far more useful in larger codebases.
Common Pitfalls
- Treating variable names as stable runtime metadata for business logic.
- Scanning
locals()and assuming exactly one matching name will always exist. - Relying on introspection behavior that changes when code is refactored.
- Using object identity lookup for immutable values that may be interned or reused.
- Solving a logging problem with reflection instead of explicit key value data structures.
Summary
- Python objects do not carry one guaranteed variable name.
- Explicit name passing is the simplest and most reliable pattern.
- Dictionaries and dataclasses model named data directly.
locals()andglobals()lookups are debugging tools, not stable application design.- Prefer structured logging and explicit labels for maintainable diagnostics.
Related reading
- Getting the SQL from a Django QuerySet
- Getting today's date in YYYY-MM-DD in Python?
- Getting today's date in YYYY-MM-DD in Python?
- Getting TypeError ''sliceNone, None, None, 0'' is an invalid key
- Getting TypeError ''sliceNone, None, None, array0, 1, 2, 3, 4'' is an invalid key
- Git Bash won't run my python files?
- Given a list of dictionaries, how can I eliminate duplicates of one key, and sort by another
- Good Python library for AMQP
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.