Python
Variable Names
String Conversion
Programming Tips
Code Snippets

Getting the name of a variable as a string

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

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.

python
x = [1, 2, 3]
y = x
print(x is y)  # True

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.

python
1def report(name, value):
2    print(f"{name} => {value}")
3
4score = 97
5report("score", score)

This is explicit, predictable, and easy to test.

Use Dictionaries for Name Value Pairs

When names are data, store them in a dictionary.

python
1metrics = {
2    "cpu": 0.82,
3    "memory": 0.63,
4    "latency_ms": 121,
5}
6
7for name, value in metrics.items():
8    print(f"{name}: {value}")

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.

python
1value = 10
2alias = value
3
4names = [k for k, v in locals().items() if v is value]
5print(names)

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.

python
1from dataclasses import dataclass, asdict
2
3@dataclass
4class JobResult:
5    task_id: str
6    status: str
7    duration_ms: int
8
9result = JobResult(task_id="A12", status="ok", duration_ms=120)
10print(asdict(result))

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.

python
1import logging
2
3logging.basicConfig(level=logging.INFO)
4logger = logging.getLogger("app")
5
6user_id = 42
7attempt = 3
8logger.info("login attempt", extra={"user_id": user_id, "attempt": attempt})

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.

python
1def check_positive(name, value):
2    if value <= 0:
3        raise ValueError(f"{name} must be positive")
4
5count = 5
6check_positive("count", count)

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() and globals() lookups are debugging tools, not stable application design.
  • Prefer structured logging and explicit labels for maintainable diagnostics.

Course illustration
Course illustration

All Rights Reserved.