首页 > 解决方案 > 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

标签: pythonpandasfunctionnumpyalias

解决方案


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

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.


推荐阅读