Create variables from strings in Python

前端 未结 2 566
心在旅途
心在旅途 2020-12-12 04:19

Is something like the following possible in Python:

>>> vars = {\'a\': 5}
>>> makevars(vars)
>>> print a
5

So, m

相关标签:
2条回答
  • 2020-12-12 04:52

    I think this works:

    locals().update(vars)
    
    0 讨论(0)
  • 2020-12-12 04:56

    It's possible, sometimes, but it's generally a very bad idea. In spite of their name, variables themselves should not be variable. They're part of your code, part of its logic. Trying to 'replace' local variables this way makes code inefficient (since Python has to drop some of its optimizations), buggy (since it can accidentally replace something you didn't expect), very hard to debug (since you can't see what's going on) and plain unreadable. Having 'dynamic values' is what dicts and lists and other containers are for.

    0 讨论(0)
提交回复
热议问题