在IPython中导入时的最佳做法 [英] Best practices when importing in IPython

查看:147
本文介绍了在IPython中导入时的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个.py文件,它会在第一个单元格中的某些IPython会话开始时定期导入,但也会从其他非交互式会话中导入,因为它包含可以在其中运行的函数在非交互模式下批处理。

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.

由于我使用IPython和 - pylab = inline 选项,numpy和matplotlib函数已经导入,但是当批量运行时只需 python mymodule.py 必须专门导入numpy函数。

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.

最后我想出了双重导入在IPython会议期间,我不太喜欢这样的事情。

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?

推荐答案

重复导入不是问题。无论在程序中导入模块多少次,Python都只运行一次代码,只生成模块的一个副本。第一个之后的所有导入仅仅引用已经加载的模块对象。如果您来自C ++背景,您可以想象所有模块都具有隐含的包含保护。

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.

这篇关于在IPython中导入时的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆