python - Python:如何确保函数中使用的模块别名正确?
问题描述
我正在尝试使任何人都可以使用函数 foo 。如何确保他们正在导入具有特定别名的模块?
def foo(object):
objdtypes = (list, tuple, np.ndarray, pd.core.series.Series)
if isinstance(object,objdtypes):
print("It's there")
现在我正在做这样的事情,如果他们必须为 numpy 和 pandas 使用不同的别名,这似乎是不可持续的。
def checkAlias():
while True:
try:
np.BUFSIZE
pd.BooleanDtype.name
return True
except NameError:
print("\n" +
"Please add the following commands to your script and try again:\n" +
"import numpy as np\n"+
"import pandas as pd")
return
解决方案
在函数内导入包,而不是依赖全局范围。
def foo(obj):
import pandas as pd
import numpy as np
objdtypes = (list, tuple, np.ndarray, pd.core.series.Series)
if isinstance(obj, objdtypes):
print("It's there")
也不要object
用作变量名,因为这会影响内置的object
.
推荐阅读
- laravel - 无法尝试以与附加字段的一对多关系插入数据
- javascript - 猫头鹰旋转木马 - 在导航按钮中间放置一个图像计数器
- qt - 如何借助布局在 QGraphicWidget 中排列小部件和形状?
- node.js - Mongo Change Streams running multiple times (kind of): Node app running multiple instances
- coldfusion - 在 ColdFusion 查询中添加 AND 语句
- r - 将矩阵中的每一行除以向量中的对应行
- ibm-watson - 训练 ibm watson 发现
- ios - Apple Watch:这是让 Apple Watch 应用获取新数据的好方法吗?
- javascript - vue-cli v3 与 node.js firebase 函数,firebase 托管(错误:在函数源目录中找不到 npm 包)
- python - 将值附加到python字典中的键