Best practices when importing in IPython

雨燕双飞 提交于 2019-12-12 12:00:42

问题


I'm writing a .py file which will be regularly imported at the start of some of my IPython sessions in the first cells but will also be imported from other non-interactive sessions, since it contains functions that can be run in batch in non-interactive mode.

It is basically a module containing many classes and functions that are very common.

Since I'm using IPython with the --pylab=inline option, numpy as well as matplotlib functions are already imported, but when run in batch with a simple python mymodule.py the numpy functions have to be imported specifically.

At the end I'd come up with double imports during the IPython session, a thing I don't like very much.

What is the best practice in this case? Isn't importing modules twice a bad practice?


回答1:


Repeated imports aren't a problem. No matter how many times a module is imported in a program, Python will only run its code once and only make one copy of the module. All imports after the first will merely refer to the already-loaded module object. If you're coming from a C++ background, you can imagine the modules all having implicit include guards.



来源:https://stackoverflow.com/questions/22144748/best-practices-when-importing-in-ipython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!