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?
I don't see what would be the advantage of it, also would make your code harder to understand. So no I don't think it is a good idea.
There is no guarantee that
vars()['myvariable'] = 'Some value'
andmy variable = 'Some value'
have the same effect. From the documentation:This code is simply wrong.
This is a bad idea, since it gets much harder to analyze the code, both for a human being looking at the source, and for tools like pylint or pychecker. You'll be a lot more likely to introduce bugs if you use tricks like that. If you think you need that feature at some time, think really hard if you can solve your problem in a simpler and more conventional way. I've used Python for almost 20 years, and never felt a need to do that.
If you have more dynamic needs, just use a normal dictionary, or possibly something like json.
One of the great things with Python, its dynamic nature and good standard collection types, is that you can avoid putting logic in text strings. Both the Python interpreter, syntax highlighting in your IDE, intellisense and code analysis tools look at your source code, provides helpful suggestions and finds bugs and weaknesses. This doesn't work if your data structure or logic has been hidden in text strings.
More stupid and rigid languages, such as C++ and Java, often makes developers resort to string based data structures such as XML or json, since they don't have convenient collections like Python lists or dicts. This means that you hide business logic from the compiler and other safety checks built into the language or tools, and have to do a lot of checks that your development tools would otherwise do for you. In Python you don't have to do that ... so don't!
Pros:
Cons:
pylint
dict
) rather than reusing a namespace dict, making it a mess in the processIn brief, at the abstraction level Python's language and runtime features are designed for, it's only good in small, well-defined amounts.
I think it's preferable to use a dictionnary if it's possible:
I think it's more pythonic.