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.
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.
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 :
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.
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.