Search code examples
pythonimportmodulefunction-call

Is a function grabbed from the 'origin-module' every time I call it?


I have a fundamental question:

I have two files. One of them, work.py, contains my script and the other, mytools.py, all my functions.

In work.py, I import, i.e. the module like so:

import mytools as mt

Somewhere in the code in work.py it'll say something like:

mt.do_something()

Does that mean it'll (i) call the function from an 'imported copy' or (ii) will the function be called directly from the module, in other words, is there a constant link between work.py and the file mytools.py where the module was imported from?

As explanation for why I'm asking this... If the call is made directly to the original module, I could make small tweaks to the parameters of single functions while work.py is running -- of course during waiting times/pause.


Solution

  • The import system in Python has 2 phases:

    1. Searching the module
    2. Loading it to create a module object

    The second step consists in reading and "executing" the source contained in the module file to create a module object in memory.

    In Python 3.4 and later, if for a reason or another the source of the module changes during the execution of your script, you can reload it.

    from importlib import reload
    import foo
    
    # changes in foo
    
    foo = reload(foo)
    

    This answer gives you details about this.