-3

How to can I print the name of argument from the function in Python:

def general_info(dataset):
    print('Info on dataset {}:').format( ??? )


general_info(df_visits)

The output I expect:

'Info on dataset df_visits:'
khelwood
  • 55,782
  • 14
  • 81
  • 108
Oleg R
  • 33
  • 4
  • 1
    And what if the value being passed is referenced by more than one identifier, or none (e.g. `general_info("hi")` or `general_info(some_seq[index])`? The name isn't an attribute of the value. – jonrsharpe Jun 13 '21 at 11:50
  • Thank you very much @jonrsharpe for pointing out the relevant answer to my question. **kwargs indeed helps me to get an argument name printed. Unfortunately, I still do not know how to place it inside of my string to make it part of the code. – Oleg R Jun 13 '21 at 12:20

2 Answers2

0

You can get the local name of the parameter this way:

def general_info(dataset):
    print(f"Info on {dataset=}")

But you cannot retrieve the name that was used in the call. It might not even have a name, or it might have more than one.

For example, what name would you expect to see printed in response to this?:

general_info("FRED") 

Or for this, would you expect to see a or b?:

a = "FRED"
b = a
general_info(a)

The name is not an attribute of the value.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
0

Perhaps using **kwargs maybe helps you here, since you can treat it as any dictionary and what you actually want is to print the keys.

def general_info(**kwargs):
    for k,v in kwargs.items():
        print(k)
        print(f'Info on dataset {k}:')


general_info(df_visits=[], some_list=[1], some_str="qwerty")
kakou
  • 636
  • 2
  • 7
  • 15