如何防止一个模块被导入两次? [英] How to prevent a module from being imported twice?

查看:21
本文介绍了如何防止一个模块被导入两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写python模块时,有没有办法防止它被客户端代码导入两次?就像 c/c++ 头文件一样:

When writing python modules, is there a way to prevent it being imported twice by the client codes? Just like the c/c++ header files do:

#ifndef XXX
#define XXX
...
#endif

非常感谢!

推荐答案

Python 模块不会多次导入.只运行两次 import 不会重新加载模块.如果要重新加载它,则必须使用 reload 语句.这是一个演示

Python modules aren't imported multiple times. Just running import two times will not reload the module. If you want it to be reloaded, you have to use the reload statement. Here's a demo

foo.py 是一个单行模块

print("I am being imported")

这是多次导入尝试的屏幕记录.

And here is a screen transcript of multiple import attempts.

   >>> import foo
   Hello, I am being imported
   >>> import foo # Will not print the statement
   >>> reload(foo) # Will print it again
   Hello, I am being imported

这篇关于如何防止一个模块被导入两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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