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.