将python模块导入例程或类定义有什么问题吗

将python模块导入例程或类定义有什么问题吗

本文介绍了将python模块导入例程或类定义有什么问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近回答了一个并提供此例程作为解决方案:

I recently answered a SO question and provided this routine as a solution:

def set_fontsize(fig,fontsize):
    import matplotlib
    """
    For each text object of a figure fig, set the font size to fontsize
    """
    if not isinstance(fig,matplotlib.figure.Figure):
        raise Exception("fig is not a matplotlib.figure.Figure")

    for textobj in fig.findobj(match=matplotlib.text.Text):
        textobj.set_fontsize(fontsize)

我进口了 matplotlib 进入 set_fontsize(图,字体大小)的定义,因为无法保证使用此例程的人会导入matplotlib at更全球化的范围(更好的术语?)。特别是因为许多matplotlib示例使用此导入调用例程: import matplotlib.pyplot作为plt

I imported matplotlib into the definition of set_fontsize(fig,fontsize) because it's not guaranteed that someone using this routine would import matplotlib at a more-global scope (better terminology?). Especially since many of the matplotlib examples invoke routines using this import: import matplotlib.pyplot as plt.

是否存在我导入matplotlib会导致冲突的实例?

Are there instances where my import of matplotlib would cause a conflict?

是否有任何效率成本?

Are there any efficiency costs?

如果 fig 是 matplotlib.figure.Figure ;一个不需要导入模块的替代方案?

Is there a preferable/more-common alternative to test if fig is an instance of matplotlib.figure.Figure; an alternative that does not require importing the module?

推荐答案

导入内部函数和类没有任何问题 - 这是一个有用的方法例如,处理相互递归的导入(其中两个文件都导入另一个)。

there's nothing wrong with importing inside functions and classes - it's a useful way of handling mutually recursive imports (where two files each imports the other), for example.

然而, 检查类型是否错误一个论点。惯用的python将检查无花果的类型。相反,只要滥用失败就会失败。这是因为你正在打破鸭子打字 - 人们不能用像fig工作的对象来调用你的例程,即使他们想要(一个明显的例子是测试模拟;另一个例子是有人写matplotlib的替代品,有相同的API,但看起来或工作得更好。)

however, there is something wrong with checking the type of an argument. idiomatic python would not check the type of fig. instead, just let misuse fail wherever it fails. this is because you are breaking "duck typing" - people cannot call your routine with objects that "work like" fig, even if they want to (an obvious example is testing mocks; another example is someone writing a replacement for matplotlib that has the same API, but looks or works better).

因此,对于那里的代码,根本没有必要进行导入。只需使用 fig

so, for the code you have there, it is not necessary to have the import at all. just use fig.

更常见的是,导入在首次使用时会被缓存,因此您通常不需要对效率感到担忧(我不是说它很完美,但在担心之前你需要对它进行分析)。

more generally, imports are cached when first used, so you typically don't need to worry much about efficiency (i'm not saying it's perfect, but it's the kind of thing you need to profile before worrying about).

这篇关于将python模块导入例程或类定义有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 04:04