简体   繁体   English

可以在函数内部导入sys来检查是否已导入模块吗?

[英]Is it okay to import sys inside a function to check if a module has been imported?

I want a function to quickly check if a module is present before running other lines in the function. 我希望函数在运行函数中的其他行之前快速检查是否存在模块。 It may execute in several other programs in a large code base and I don't want to import sys at the top wherever it is run. 它可能会在大型代码库的其他几个程序中执行,并且我不想在运行它的顶部都导入sys

This answer explains the procedure to check if a module is present. 此答案说明了检查模块是否存在的过程。

>>> import sys
>>> 'unicodedata' in sys.modules
False
>>> import unicodedata
>>> 'unicodedata' in sys.modules
True

Here a number of people voice opinions on when it is okay to import inside a function. 在这里 ,许多人对何时可以导入功能发表了意见。

Is the following specific usage okay? 可以使用以下特定用法吗?

def some_function(foo):
    import sys
    if 'pandas' in sys.modules:
        if isinstance(foo, pd.DataFrame):
            # function continues
    else:
        print("pandas has not been imported in the code you are testing")

The use case is checking first if a pandas data frame fulfills various conditions and if so do other operations. 用例首先检查熊猫数据帧是否满足各种条件,如果满足,则执行其他操作。 Thing is, looking at the code base I can't always be sure if the thing I am testing the function on is a dataframe at all, so have been doing if is instance(variable, pd.DataFrame) . 事情是,看着代码库,我不能总是确定我正在测试该函数的东西是否根本就是一个数据帧,所以一直在做if is instance(variable, pd.DataFrame) But what if the function is imported somewhere and run where there is no pandas at all? 但是,如果该函数导入到某个地方并在根本没有熊猫的地方运行怎么办? I'd rather it just realised that, than crashed the whole program or imported pandas unnecessarily. 我宁愿它只是意识到,而不是不必要地使整个程序或导入的熊猫崩溃。

You appear to be confused between a library being installed versus a library having been imported. 您似乎对正在安装的库与已导入的库之间感到困惑。

Your use-case seems to be concerned with Pandas not being installed. 您的用例似乎与未安装Pandas有关。 You can't test for this possibility with sys.modules . 您无法使用sys.modules测试这种可能性。 Just have your code import Pandas, and handle the ImportError thrown if it is not available: 只需让您的代码导入Pandas,并处理如果不可用则引发的ImportError

try:
    import pandas as pd

    def is_dataframe(obj):
        return isinstance(obj, pd.DataFrame)
except ImportError:
    def is_dataframe(obj):
        return False

The above code codifies the test for the dataframe type that will continue to work if Pandas is not installed. 上面的代码整理了对数据框类型的测试,如果未安装Pandas,该测试将继续起作用。

If your code needs to take into account the possibility that some third-party library returns a dataframe, just use the above code to test for that contingency (but only if you can't make your code work in some other way, like just catching the exception if something is not the type you expected to handle). 如果您的代码需要考虑某些第三方库返回数据帧的可能性,则只需使用上面的代码来测试这种偶然性(但前提是您不能以其他方式使代码工作,例如仅捕获如果不是您期望处理的类型,则为例外)。 Don't try to second-guess if Pandas is actually being used somewhere. 如果熊猫确实在某个地方被使用,请不要去猜测。 Either you handle dataframes or you don't, there is no need to make this dynamic. 无论是处理数据帧还是不处理数据帧,都无需使其动态化。 It's not as if the isinstance(obj, pd.DataFrame) test will throw an exception if obj is not a dataframe, there is no risk here . 如果obj不是数据帧,则isinstance(obj, pd.DataFrame)测试isinstance(obj, pd.DataFrame)不会引发异常,这里没有风险

Note that if you do try to test for the module being imported, detect that it wasn't, and only then another module imports Pandas , you made the wrong call and your code breaks. 请注意,如果您确实尝试测试要导入的模块,请检测它是否不是,然后只有另一个模块导入Pandas ,您才进行了错误的调用,并且代码中断了。 Python is a dynamic language and imports can be done at any time during the runtime of the program. Python是一种动态语言,可以在程序运行时随时进行导入。

Otherwise, if Pandas is installed, and some third-party module imports Pandas to do their work and you are worried that they might, there is no need for your code to worry about this . 否则,如果安装了熊猫,以及一些第三方模块导入熊猫做他们的工作,你是担心他们可能, 也没有必要为您的代码到这个担心 There is no need for you to see if a third-party module is using Pandas or not, it won't make a difference to your code. 您无需查看第三方模块是否正在使用Pandas,就不会对您的代码产生影响。 Pandas is then just an implementation detail of another module. 熊猫只是另一个模块的实现细节。

Lastly, if a third-party module imports Pandas, your own module won't also see it . 最后,如果第三方模块导入了Pandas,则您自己的模块也不会看到它 You need to use import statements for all dependencies for that module, it doesn't matter what another module has imported here, as each module is a separate namespace. 您需要为该模块的所有依赖项使用import语句,这里导入另一个模块都没有关系,因为每个模块都是单独的命名空间。 You can't just use pd.DataFrame without an import statement (or other means of binding the name pd to the module object), regardless of other modules having imported it. 您不能仅pd.DataFrame没有import语句的情况下使用pd.DataFrame (或将名称pd绑定到模块对象的其他方式),而不管其他模块是否pd.DataFrame其导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM