Python 3.6.5

Using this answer as a guide, I attempted to see whether some modules, such as math were imported.

But Python tells me they are all imported when they are not.

>>> import sys
>>> 'math' in sys.modules
True
>>> 'math' not in sys.modules
False
>>> math.pi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> import math
>>> 'math' in sys.modules
True
>>> math.pi
3.141592653589793

推荐答案

to explain this, let's define this function:

def import_math():
    import math

import_math()

the above function will import the module math, but only in its local scope, anyone that tries to reference math outside of it will get a name error, because math is not defined in the global scope.

any module that is imported is saved into sys.modules so a call to check

import_math()
print("math" in sys.modules)

will print True, because sys.modules caches any module that is loaded anywhere, whether or not it was available in the global scope, a very simple way to define math in the global scope would then to

import_math()
math = sys.modules["math"]

which will convert it from being only in sys.modules to being in the global scope, this is just equivalent to

import math

which defines a variable math in the global scope that points to the module math.

now if you want to see whether "math" exists in the global scope is to check if it is in the global scope directly.

print("math" in globals())
print("math" in locals())

which will print false if "math" wasn't imported into the global or local scope and is therefore inaccessable.

Python相关问答推荐

无法通过python-jira访问jira工作日志(log)中的 comments

NP.round解算数据后NP.unique

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

在Python中动态计算范围

Pandas计数符合某些条件的特定列的数量

在单个对象中解析多个Python数据帧

字符串合并语法在哪里记录

如何保持服务器发送的事件连接活动?

需要帮助重新调整python fill_between与数据点

在两极中过滤

Pandas 数据帧中的枚举,不能在枚举列上执行GROUP BY吗?

如何在验证文本列表时使正则表达式无序?

在Django中重命名我的表后,旧表中的项目不会被移动或删除

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

随机森林n_估计器的计算

如何将列表从a迭代到z-以抓取数据并将其转换为DataFrame?

Stats.ttest_ind:提取df值

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

如何强制SqlalChemy指向与连接字符串的默认架构不同的架构

逐个像素图像处理的性能问题(枕头)