1

Currently in my code, I have been using globals()['value%s' % str(int(y))] to be able to set a name of a variable using strings, but now I have run into a problem in that this variable is a global and I don't want it to be a global. Is there a way to change the code such that I can create a variable name using a string without creating a global variable?

FoxEvolved
  • 29
  • 1
  • 6
  • 1
    Is there a reason you're not using a `dict` for this? – Blorgbeard Jun 24 '19 at 23:25
  • Why do you want to set a variable name from a string? This is what dicts are for. – PMende Jun 24 '19 at 23:25
  • You can't edit local variables dynamically, because they're accessed by index under the hood, not name. Use a dictionary! https://stackoverflow.com/a/8028772/ – Dmiters Jun 24 '19 at 23:26
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Carcigenicate Jun 24 '19 at 23:32

1 Answers1

0

You can't update the locals dictionary. A more robust and flexible approach would be to use a dict local to the function:

def foobar():
    dct = {}
    dct[f'value{y}'] = 'something'
    ... 
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Sol I just tried `locals()['value%s' % str(int(y))] = 8`, and it appears to work. `locals()['value%s' % str(int(y))]' return 8, and `locals()` returns a bunch of variable names including `value5` (as y was 5). So it Python doing something behind my back to fool me into thinking it works? – Deepstop Jun 24 '19 at 23:32
  • 2
    @Deepstop Perhaps you've run it outside function? On the module scope, `locals` and `globals` are the same, so setting to `locals` will work there. – heemayl Jun 24 '19 at 23:34
  • Makes sense. Thanks. – Deepstop Jun 24 '19 at 23:35