5

To illustrate the issue I am having, please consider the following. I have two .py files, one named main.py and the other named mymodule.py. They are both in the same directory.

The contents of main.py:

from mymodule import myfunction

myfunction()

The contents of mymodule.py:

def myfunction():
    for number in range(0,10):
        print(number)

print("Hi")

I was under the impression that importing a function would only import that function. However, when I run main.py, this is what I get:

Hi
0
1
2
3
4
5
6
7
8
9

Why is print("Hi") being called? It isn't part of the function I imported!

wim
  • 338,267
  • 99
  • 616
  • 750
Dan Curry
  • 149
  • 8

3 Answers3

9

I was under the impression that importing a function would only import that function.

It seems there's an incorrect assumption about what a from-import actually does.

The first time a module is imported, an import statement will execute the entire module, including print calls made at the global scope (docs). This is true regardless of whether the mymodule was first imported by using a statement like import mymodule or by using a statement like from mymodule import myfunction.

Subsequent imports of the same module will re-use an existing module cached in sys.modules, which may be how you arrived at the misunderstanding that the entire module is not executed.

There is a common pattern to avoid global level code being executed by a module import. Often you will find code which is not intended to be executed at import time located inside a conditional, like this:

def myfunction():
    for number in range(0,10):
        print(number)

if __name__ == "__main__":
    print("Hi")
wim
  • 338,267
  • 99
  • 616
  • 750
3

In order to import something from the module Python needs to load this module first. At that moment all the code at module-level is executed.

According to the docs:

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement.

Eugene Primako
  • 2,767
  • 9
  • 26
  • 35
  • 1
    I would have add the footnote too: `In fact function definitions are also ‘statements’ that are ‘executed’; the execution of a module-level function definition enters the function name in the module’s global symbol table.` – Marco Luzzara Jul 02 '18 at 19:21
3

this question seems to be a duplicate of this one.

In short : all the code of a python file is called when importing the module. What is neither a function nor a class is usually put in a main function called here:

if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   main()

Please consider closing this thread.

CharlesG
  • 329
  • 3
  • 12