-1

I have a number of global variables in my script (e.g. group_1, group_2, group_3) and I am trying to refer to them inside a function.

def plot(group_number):
   return(f"group_{group_number}")

I would like the function in this case to return the global variable group_2 when I run plot(2). Is there a way to turn this string "group_2" into the variable group_2?

Jimmy
  • 127
  • 10

1 Answers1

1

Global variables are available through the dict returned by globals(). So,

>>> group_1 = "one"
>>> group_2 = "two"
>>> group_3 = "three"
>>> 
>>> def plot(group_number):
...     return globals()[f"group_{group_number}"]
... 
>>> plot(2)
'two'
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 1
    @Jimmy You may very well like the answer. Many beginners want to do something like that. But doing it it is nearly always unnecessary. It is also brittle, hard to maintain, and a potent source of bugs. The advice from the duplicate was to use a dictionary or a list. That is good advice. I know you can't see why this is a duplicate question: it's because it tells you your approach is wrong. But if you present this sort of thing to a code review, you may find your colleagues unsympathetic. – BoarGules May 16 '22 at 16:31