Search code examples
pythonvariablespython-3.5dynamic-variables

Is it a good idea to dynamically create variables?


I recently found out how to dynamically create variables in python through this method:

vars()['my_variable'] = 'Some Value'

Thus creating the variable my_variable.

My question is, is this a good idea? Or should I always declare the variables ahead of time?


Solution

  • I think it's preferable to use a dictionnary if it's possible:

    vars_dict = {}
    vars_dict["my_variable"] = 'Some Value'
    vars_dict["my_variable2"] = 'Some Value'
    

    I think it's more pythonic.