1

I'm writing a function to draw plots of dataframes and I would like to name the plots according to the name of the dataframe passed to the function. The first line of the plotter function is:

def plotter(data):

Say the data frame to be passed is df1, I'm wondering how could I get the string 'df1' when calling plotter(data=df1)?

Ignacio Alorre
  • 7,307
  • 8
  • 57
  • 94
dyluns
  • 155
  • 9
  • You can't, as only the reference is stored in `df1` and in the context of the `plotter` function the dataframe is called `data`. – creyD Jan 18 '21 at 13:26
  • 3
    You generally cannot; things do not have names, names have things. You can inspect the source code or stack, but there is no guarantee you will find a name there. For example, what would you expect the code to do when the function is called as ``plotter(**kws)`` or ``plotter(df_factory())``? – MisterMiyagi Jan 18 '21 at 13:26
  • 3
    What you could do is to deliver the name alongside the dataframe itself, but this would mean to extend the signature. – creyD Jan 18 '21 at 13:26

1 Answers1

1

You can do this:

from varname import nameof

def plotter(data, name_df):
  # name_df is a string which is is "df1", then you can add to the plot

plotter(df1, nameof(df1))
Ignacio Alorre
  • 7,307
  • 8
  • 57
  • 94