Reputation: 3007
I'd like to know what the variable name was that was passed into a function. Is this possible in Python?
Consider this case:
john = 199
def foo(userId:int)->float:
age = get_age_by_id(userId)
return age
I'd like to log something like:
foo(john)
>>> Called with userId = 199 # john
So, I am looking for a way to "peek" at the variable name that was passed as an argument to the function.
Any ideas?
Upvotes: 0
Views: 1132
Reputation: 71464
The closest thing to a solution is to inspect
the stack and look for a variable with a matching value. Note that you can't actually know for certain which of those variables (if any) was the source of the value that your function received.
import inspect
def foo(age: int) -> None:
caller_vars = [
var
for var, val in inspect.stack()[0].frame.f_back.f_locals.items()
if val == age
]
print(f"Called with {age} = {', '.join(caller_vars) or '???'}")
foo(199) # Called with 199 = ???
john = 199
foo(john) # Called with 199 = john
eric = 199
foo(john) # Called with 199 = john, eric
Upvotes: 3
Reputation: 180331
Variable names are not passed into a function. Variable values are. Those values may or may not be conveyed via variables at the point of a given call, but if they are, the variable names are not part of the semantics of the call. That is, the names are not available to the code in the function.
It's unclear why you ask. If it's for debugging-related purposes then you are probably looking for a Python debugger. There are several, including pdb
, which comes with Python. If it's because the function inherently requires a name to go along with the value, then you need to redesign the function to accept more or different parameters.
Upvotes: 4