Skip to content

Instantly share code, notes, and snippets.

@DeflateAwning
Created August 1, 2023 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeflateAwning/6a7c3f8a4070bcec267536b624d08fd8 to your computer and use it in GitHub Desktop.
Save DeflateAwning/6a7c3f8a4070bcec267536b624d08fd8 to your computer and use it in GitHub Desktop.
A simple python function to get the name of a variable from a calling scope
def calling_var_name(obj) -> str:
""" Returns the name of the variable that was passed in. """
caller_frame = inspect.currentframe().f_back.f_back
while hasattr(caller_frame, 'f_locals'):
list_of_obj_names = ([name for name, value in caller_frame.f_locals.items() if value is obj])
if len(list_of_obj_names) > 0:
return list_of_obj_names[0]
else:
caller_frame = caller_frame.f_back
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment