Python:如何确保函数中使用的模块别名是正确的?

2024-05-15 21:38:59 发布

您现在位置: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

Tags: 函数importnumpytruepandasreturnobjectfoo
2条回答

在函数中导入包,而不是依赖全局范围

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

当有人导入您的函数时,将使用您使用的别名导入任何必需的模块。例如,您可以创建一个名为mymodule.py的文件,其中包含:

import numpy as np

def myfunc(arg):
    return np.sin(arg)

如果随后打开Python终端会话并使用:

from mymodule import myfunc

print(myfunc(2))
0.9092974268256817

它会很好地工作。如果在终端会话中使用不同的别名导入numpy,它甚至可以工作,例如

import numpy as blah
from mymodule import myfunc

print(myfunc(2))
0.9092974268256817

导入myfunc后,如果您查看:

myfunc.__globals__
{'__builtins__': {'ArithmeticError': ArithmeticError,
...
'__file__': 'module.pyc',
 '__name__': 'module',
 '__package__': None,
 'myfunc': <function module.myfunc>,
 'np': <module 'numpy' from '/usr/local/lib/python2.7/dist-packages/numpy/__init__.pyc'>}

您可以看到,它包含numpy的预期别名(np),这就是它将使用的别名

相关问题 更多 >