【发布时间】:2011-10-28 08:53:27
【问题描述】:
可能重复:
Should Python import statements always be at the top of a module?
我最近回复了SO question 并提供了这个例程作为解决方案:
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(fig,fontsize) 的定义中,因为不能保证使用此例程的人会在更全局的范围内导入 matplotlib(更好的术语?)。特别是因为许多 matplotlib 示例使用此导入调用例程:import matplotlib.pyplot as plt。
是否存在我导入 matplotlib 会导致冲突的情况?
是否有任何效率成本?
是否有更好/更常见的替代方法来测试fig 是否是matplotlib.figure.Figure 的实例;不需要导入模块的替代方法?
【问题讨论】:
-
@carl,这个问题及其答案几乎涵盖了我的问题。
标签: python import module instance