1

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.

Mat
  • 515
  • 5
  • 10
  • 3
    A *module* is imported, `mt`, and that module object has an attribute, `do_something` which is a function. No copies are made. "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." I am not sure what you mean by this. What do you mean, "make small tweaks"? Do you mean literally modify the source code? Because that won't affectd anything once the modules have been loaded – juanpa.arrivillaga Jan 24 '19 at 17:06
  • 1
    You may be intersted in this answer: https://stackoverflow.com/a/437591/1388292 – Jacques Gaudin Jan 24 '19 at 17:15
  • 2
    The module is not the source file. The module is generated from the source file. It looks like you really want to know whether Python will reread the source file every time. – user2357112 Jan 24 '19 at 17:21
  • thanks @juanpa.arrivillaga -- yes, I mean to literally change the code in the file containing my functions. But you answered my question as to how loading module works. – Mat Jan 24 '19 at 17:23
  • @JacquesGaudin -- fantastic, thank you!! I had no idea this existed. That takes care of my problem. – Mat Jan 24 '19 at 17:24

1 Answers1

1

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.

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75