Is it a good idea to dynamically create variables?

后端 未结 5 1909
故里飘歌
故里飘歌 2020-12-06 23:58

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

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

Thus creat

5条回答
  •  有刺的猬
    2020-12-07 00:09

    Pros:

    • adds another level of indirection, makes the environment more dynamic
      • in particular, allows to avoid more code duplication

    Cons:

    • not applicable for function namespaces (due to optimization)
    • adds another level of indirection, makes the environment more dynamic
      • "lexical references" are much harder to track and maintain
        • if created names are arbitrary, conflicts are waiting to happen
        • it's hard to find the ins and outs in the code base and predict its behaviour
        • that's why these tricks may upset code checking tools like pylint
    • if variables are processed in a similar way, they probably belong together separately from others (in a dedicated dict) rather than reusing a namespace dict, making it a mess in the process

    In brief, at the abstraction level Python's language and runtime features are designed for, it's only good in small, well-defined amounts.

提交回复
热议问题