Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

9
  • 1
    Yes, this would work, but I don't know why you would do this - remember Explicit is better than implicit, and "Readability Counts". This is just a bad idea IMHO. Commented Jul 2, 2014 at 18:31
  • 8
    @chris-piekarski Thanks for this answer. One reason for wanting to do such thing is when you need to communicate with a 3rd-party software that expects inputs passed as local variables, and at compile time you don't know the variables that it expects (I'm creating a Paraview plugin, for example, and it imposes this kind of constraints). Commented Jan 8, 2015 at 17:42
  • 4
    Be aware that this will not work in Python 3 within a function execution context. It still is fine in the top level (module) context. If you need to create a module variable, I would suggest editing the globals() dict, or calling setattr() on the module object. Commented Jun 29, 2015 at 12:44
  • 2
    Let me also underline that, in general, this poses a security risk when the keys or values are provided by external data (user input, a file or anything). The usual warnings when using eval/exec apply. You don't want someone to set the value to "send_me_all_your_private_data()" and get it executed on your machine. Commented Jun 29, 2015 at 12:48
  • 4
    Actually, this is a very good answer, and the only solution in specific circumstances. Say you have an array that represents an inventory. Say this inventory can have containers inside of it, and these containers has an inventory of its own, representing the items the container is holding. This is the only way that I know of to be able to store INDEXES in a string, and be able to change it, and access different indexes dynamically, e.g. if you change which container you are looking inside of. Commented Nov 16, 2016 at 19:38