0

If I do this in python 3.8.3:

globals()['any_new_variable_name'] = 'any_value_or_object_here'
print(any_new_variable_name)

It works like assignment.

Is this considered 'defined' behavior? Is variable assignment simply in a sense syntactic sugar for adding keys to the dictionary object we can access with globals()?

AturSams
  • 7,568
  • 18
  • 64
  • 98
  • 2
    I'd say, yes and yes. Python is basically powered by dictionaries. – ForceBru Dec 09 '20 at 18:09
  • Though, if you intend to use this to create variable variables, have a look at https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – Thierry Lathuille Dec 09 '20 at 18:13
  • 2
    So, interestingly, the documentation is a bit vague. IMO https://docs.python.org/3/library/functions.html#globals it says: "Return a dictionary representing the current global symbol table." which is similar to what it says about `locals()`, but of course, `locals()` warns you that changes to the returned dictionary are not guaranteed to affect the local namespace (and indeed, in current versions of CPython, they do not) – juanpa.arrivillaga Dec 09 '20 at 18:24

1 Answers1

0

Yes, it is. Globals is a special dictionary in python that stores all the created global variables. But don't use this way to assign a value to a variable! It is a bad code practice. Use traditional method instead:

variable = "value"