Is there anything wrong with importing a python mo

2019-05-30 15:41发布

问题:

Possible Duplicate:
Should Python import statements always be at the top of a module?

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)

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.

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

Are there any efficiency costs?

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?

回答1:

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.

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).

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).



回答2:

There's nothing particularly wrong with importing inside the function - although you should do it after the docstring, otherwise Python won't see the docstring - but your reasoning doesn't make any sense.

If you import at module level, and someone imports your function, the function has access to all the things in its module, including imports. Users of your function don't need to import anything specifically.