Using inspect
which is a module to access and retrieve the name of a variable passed as an argument:
import inspect
def func(df_1, df_2):
variable_name = [k for k, v in inspect.currentframe().f_back.f_locals.items() if v is df_1][0]
print(variable_name)
first_df = ..
second_df = ..
func(first_df, second_df)
inspect.currentframe()
returns the current stack frame, which represents the execution frame of the func function.
f_back
refers to the previous frame in the call stack, which in this case represents the frame of the caller function.
f_locals
is a dictionary containing the local variables in the current frame.
The list [k for k, v in inspect.currentframe().f_back.f_locals.items() if v is df_1]
iterates over the key-value pairs in the caller function's local variables and filters out the key-value pair where the value (v) is the same object as df_1.
[0]
is used to retrieve the first (and only) element from the resulting list, which corresponds to the variable name.
I hope this will help