Customize variable names through statements

Can Python in the future have a create_variable function that can be used to create a variable with a custom name? Its syntax can be similar to this:

create_variable(variable_name,variable)

In some cases, this function is very useful, and variables created using this function can also be used as normal variables.
Maybe this idea is a bit unrealistic. :wink:

What do you mean by a ā€œcustom nameā€? Something like this:

name = "spam"
# do some magic to set it to 42
print(spam) # prints 42

? If so, then yes! You can! A module’s global variables are stored in a dictionary, and you can use that like any other dictionary. Here’s what the magic looks like:

name = "spam"
globals()[name] = 42
print(spam)

And it does, in fact work! You can do something similar with setattr() for attributes of an object, and similarly for other types of namespace.

1 Like

No, what I mean is this:

variable_name='spam'
variable=1
create_variable(variable_name,variable)
print(spam)#print:1

:wink:
@Rosuav

If you mean an actual function that does this, you can make a function that modifies the caller frame’s f_locals attribute, which is now a write-through dict proxy since CPython 3.13 with the implementation of PEP 667 – Consistent views of namespaces | peps.python.org :

import sys

def create_variable(name, value):
    sys._getframe(1).f_locals[name] = value

variable_name='spam'
variable=1
create_variable(variable_name,variable)
print(spam)#print:1

There’s almost never a good use for a dynamically created variable though. Better to use a regular dict instead.

Yep! You can do exactly that with the globals() dictionary.

You may find this SO question helpful:

You need to know that this is a bad idea because it is impure coding… yet practicality beats purity.

The cleanest way to do this IMO is to first create a dictionary with the variables (names and values) you want to create

dict_variables = {'variable1':value1, 'variable2':value2}

Then update the locals() or globals(), according to your case :

locals().update(dict_variables)
#or
globals().update(dict_variables)
2 Likes

Then update the locals() or globals(), according to your case

This will not work because cpython will decide on different load opcodes for different names during compilation time based on whether they (names) are assigned or not, whether they are declared global, nonlocal, etc.

It is not possible to solve OP’s problem in cpython by design: only to work around it this or that way.

In my test cases, locals().update(...) and globals().update(...) both work perfectly (in python 3.12 at least), maybe you have a case where that does not work.

I recenty had to work with code where someone did this.
I refactored it out of the code, because it’s frankly nice when pylance is able interpret things correctly. But the trick did work.

1 Like

Example:

def foo():
    locals().update({"bar": "baz"})
    print(bar)

foo()

outputs

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    foo()
    ~~~^^
  File "test.py", line 3, in foo
    print(bar)
          ^^^
NameError: name 'bar' is not defined

Right, it does not work with locals().update(...), but work with globals().update(...).
I remember having a dirty case where I was doing globals().update(locals()).
But anyway, dynamic names are better handled within a dedicated dict.