python string to function: globals() vs sys.module vs dictionary

浪尽此生 提交于 2019-12-07 18:11:27

Using globals() is the normal way to access (and store) variables you want to access globally.

Otherwise, the usual choice is to implement a dispatch dictionary (like your option 3).

I've not seen the sys.modules approach used anywhere.

I'm only a novice Python coder (< 6 months) but to answer your question directly, it actually seems to me that sys.modules is the "best" solution if you're looking for the most flexible. Here's why:

  1. Creating a new dictionary manually seems like wasted effort when the data already exists and can be accessed using both the globals() and sys.modules approaches.
  2. The globals() and sys.modules approaches also allow you to automatically and dynamically farm (and then filter) lists of functions - useful if, like me, you were trying to automatically build GUIs/menus from all functions defined in your code.
  3. A consideration with globals() is that if you import and call the "function farmer" from another module, you'll only get the functions of the "function farmer" module itself, not the parent module. [There might be a solution for this... I've posted a separate question here and will update this response if I hear anything useful back.]
  4. Using sys.modules on the other hand, you can call the "function farmer" and get the functions of the '__ main __' module.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!