在 Python 中,当你在函数内部导入时会发生什么? [英] In Python, what happens when you import inside of a function?

查看:57
本文介绍了在 Python 中,当你在函数内部导入时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在速度和内存效率方面,在函数内部导入 Python 模块和/或函数的优缺点是什么?

What are the pros and cons of importing a Python module and/or function inside of a function, with respect to efficiency of speed and of memory?

是否在每次运行函数时重新导入,或者无论函数是否运行,在开始时都重新导入一次?

Does it re-import every time the function is run, or perhaps just once at the beginning whether or not the function is run?

推荐答案

每次运行该函数时是否重新导入?

Does it re-import every time the function is run?

没有;或者更确切地说,Python 模块基本上在每次导入时都会被缓存,因此导入第二次(或第三次、第四次……)实际上并不会强制它们再次执行整个导入过程.1

No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1

无论函数是否运行,一开始都导入一次吗?

Does it import once at the beginning whether or not the function is run?

不,只有在执行函数时才会导入.2, 3

No, it is only imported if and when the function is executed. 2, 3

至于好处:我想这取决于.如果您可能只很少运行一个函数并且不需要在其他任何地方导入模块,那么只在该函数中导入它可能是有益的.或者,如果存在名称冲突或其他原因,您不希望模块中的模块或符号无处不在,您可能只想在特定函数中导入它.(当然,对于这些情况,总是 from my_module import my_function as f.)

As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f for those cases.)

在一般实践中,它可能没有那么有益.事实上,大多数 Python 风格指南都鼓励程序员将所有导入放在模块文件的开头.

In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.

这篇关于在 Python 中,当你在函数内部导入时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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