Task
I would like to have a way to access the original name of a passed argument. I looked at the answers of
- Getting the name of a variable as a string
- How to get the original variable name of variable passed to a function
which seemed a bit complicated to me. Another idea is to write
import pandas as pd
my_var = pd.DataFrame(...)
def f(dataset: pd.DataFrame):
for name, obj in globals().items():
if id(obj) == id(dataset):
return name
f(my_var)
which returns 'my_var'. This makes sense to me and does not seem to be brittle.
However, since I did not see such an answer anywhere, I am wondering if I am missing something and this answer is actually a bad idea.
Questions
- Is this code a good/valid idea?
- If not why is a different (which?) answer better?
What am I NOT asking
I am NOT asking how to "how to get the original variable name of variable passed to a function". I am asking whether/why my suggested code is problematic. This is a different question.
Background
I want to use this as a helper function in a data analytics task, where I use the variable's name as a label for the later plot.
import pandas as pd
def f(dataset: pd.DataFrame):
return_dataframe = do_stuff(dataset)
for name, obj in globals().items():
if id(obj) == id(dataset):
return_dataframe["group"] = name
return return_dataframe
data_frame_for_plotting = pd.concat([f(data_train), f(data_test)])