0

I've got a lot of variables that their values are user's inputs. So I want if input == 0 value of variable becomes it's name! I know I can try:

Var = something if something else "var"

But in real code, "something" part is very long and code will be WET. I tried to define a function, but there is another problem:

X = 9
Y = 0

Def f(x):
   digit_finder = max(list(map(lambda x:abs(x) , re.findall(r'\d+', str(x))
   if digit_finder > 0:
     x = x
   else:
     x = str(x)
   return x
Print(f(x))
Print(f(y))
Pri
>>> 9
>>> 0.0 # I want this part returns "y"
Gone
  • 1
  • 3
  • 1
    You can't, not at least according to what you described. `0.0` (or any other object) has no idea that a reference called `Y` was ever created for it (and it shouldn't care) – DeepSpace Sep 23 '19 at 14:29
  • 2
    No, no, no. Do *not* mix code and variables. There's no (legitimate) way for `f` to even *know* the name of the variable used to hold the *value* that was passed as an argument. – chepner Sep 23 '19 at 14:30
  • @chepner `f` does not even know it received a reference (ie `Y`) and not a value (ie `0.0`) – DeepSpace Sep 23 '19 at 14:31
  • maybe this can help https://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python – Amir Abbas Sep 23 '19 at 14:32
  • @DeepSpace Yeah, I left that implied. The function *only* receives the value, whether it was provided to the call by a reference, an expression, or a literal. (Since the language is responsible for converting any of the above to a single value *before* the function call actually occurs.) – chepner Sep 23 '19 at 14:32
  • As the previous comments suggest, you can't do this. Unless you use `**kwargs` and or some dictionary to keep track of your inputs – Buckeye14Guy Sep 23 '19 at 14:42
  • @Buckeye14Guy can you write code that you are thinking to? – Gone Sep 23 '19 at 14:47
  • yea I added an example – Buckeye14Guy Sep 23 '19 at 14:58

2 Answers2

0

If you need it just for test purposes, I'd recommend you to throw exception:

def f(v):
    if v:
        return v * 2
    else:
        raise ValueError()


x = 1
y = 0
f(x)
f(y)

Result:

Traceback (most recent call last):
  File "C:/.../test.py", line 11, in <module>
    f(y)  <----------------------------------- here is variable name
  File "C:/.../test.py", line 5, in f
    raise ValueError()
ValueError
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
0

As the comments all suggest, you can't really do what you want. Anyway you look at it, you will to do some additional work. You could try this with keyword arguments if you really need to return 'y'.

import re

def f(**kwargs):
   # make sure kwargs has one element otherwise raise some error?
   name, value = tuple(kwargs.items())[0]
   digit_finder = max(list(map(lambda x:abs(int(x)) , re.findall(r'\d+', str(value)))))
   if digit_finder > 0:
     return value

   return name

x = {'x': '9'}
y = {'y': '0'}

f(**x)
f(**y)
Buckeye14Guy
  • 831
  • 6
  • 12