0

my_module.py

    
print('Module Imported...')

test = 'Test String'


def find_index(to_search, target):
    '''Find the index of a value in a sequence'''
    for i, value in enumerate(to_search):
        if value == target:
            return i
    return 'none'

intro.py

from my_module import find_index

courses = ['Math', 'Arts', 'History', 'English']

index = find_index(courses, "History")
print(index)

When running this the result is:

Module Imported...
2

I want to know why is my program printing the 'Module Imported...' string even though I am only importing the find_index function.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 2
    you would have to put that code within `if __name__ == '__main__':` https://stackoverflow.com/questions/419163/what-does-if-name-main-do – Cory Kramer Jan 22 '21 at 20:34

2 Answers2

2

When you import from a module, only the names that you specify are bound in the importing scope, but all of the top level code in that module is executed.

This is important because some of the names that you import might depend on code that you didn't explicitly import -- for example, that module's own imports, the definitions of private functions/classes/objects that the exported functions depend on, etc! It would be extremely unwieldy if you had to understand all of the dependencies of the module you're importing and explicitly import each dependency to make sure that the things you're actually trying to use will work correctly.

Needless to say, you should not have top-level module code that you don't want to get executed on every import. This is why you'll often see blocks in scripts like:

if __name__ == '__main__':
    # actually do stuff
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

By importing a file the initial code gets run and the from my_module import only scopes of what can be used so the file can be loaded in faster but the first code gets always run

Freestyle
  • 1
  • 1