Created
August 1, 2023 17:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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