True difference between 'normal' and 'inside-function' imports in Python

145 Views Asked by At

With respect to this question: local-import-statements-in-python, quoted here at the time of my asking:

I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea?

def Process():
    import StringIO
    file_handle=StringIO.StringIO('hello world')
    #do more stuff

for i in xrange(10): Process()

A little more justification: it's for methods which use arcane bits of the library, but when I refactor the method into another file, I don't realize I missed the external dependency until I get a runtime error.

I wish to ask the following:

  • What is eventually the true difference between importing a module at the top of a .py file and importing it from inside a function definition?

For instance, I personally experienced a particular problem with the win32com.client module where my script crashed when I imported the module at the top of my file but stangely enough it seemed to execute normally after I called the import statement from within the function that was in turn calling one of its methods.

For more info on this, please see my other post here: How to launch win32 applications in separate threads in Python.

I am suspecting that this behaviour has something to do with the locals() and globals() being differently updated or not updated at all in some cases... Please enlighten me.

1

There are 1 best solutions below

2
On

There is no difference in how the imports are treated (with the caveat that, as the answer to that question states, the imported name is only available within the scope of the code that imported it: so if it's done inside a function, the name is local to that function).

The main difference - and the only good reason why you might want to do an import inside a function - is that anything at top level is executed when the module itself is first imported. This can lead to the possibility of circular imports: if two files both import each other at the top level, the circularity cannot be resolved and Python will raise an exception.