4

How can I get name of input argument in function?

Here is example

a=1
b=2
c=3
def test(x):
    print(?)

test(b)

and result should be

b

I think this is easy problem...? But not to me :)

ssw101
  • 195
  • 2
  • 2
  • 8

1 Answers1

0

Due to the fact that multiple variables can have the same value, the below function returns a list of all the variable names that holds the value passed in as argument:

a = 1
b = 2
c = 3
def test(x):
    print([k for k, v in globals().items() if v == x])

test(b)

Output:

['b']

Of course, you can always return after the first occurrence of a match:

a = 1
b = 2
c = 3
def test(x):
    for k, v in globals().items():
        if v == x:
            return print(k)

test(b)

Output:

b
Red
  • 26,798
  • 7
  • 36
  • 58