0

**This is in python **

For example:

If my function is def func(df_1, df_2)

and my code looks like this when implemented: func(first_df, second_df)

is there a way to print 'first_df' to the console?

I've tried print(first_df) but it prints the entire *DataFrame. I don't want that, I want it to print 'first_df'

Zero
  • 1,807
  • 1
  • 6
  • 17
  • 1
    Does this answer your question? [Getting the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) – G. Anderson Jun 23 '23 at 20:10

2 Answers2

0

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

Ahmad Abdelbaset
  • 295
  • 2
  • 11
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?** – Jeremy Caney Jun 24 '23 at 00:17
0

If you want to print 'first_df', then use the raw string 'r':

print(r'first_df')

Is this what you asked for?