1 of 7

Modules

2 of 7

Modules

  • A Python program may consist of multiple modules (.py files) of code
  • Modules may import other modules
    • Multiple files embedded into one another
    • Forming one large program

Where does a Python program start?

3 of 7

Where does a Python program start?

  • In most languages, a program always starts with a function called main
  • If you execute/run a Python file/module, it will start at the first executable statement
    • The first unindented executable statement
    • Function definitions are not executable

  • Many Python programmers set up a main function like this

def main():

print("Hello World!")

if __name__ == "__main__":

main()

https://realpython.com/python-main-function/

4 of 7

if __name__ == "__main__":

  • This block distinguishes between whether the module has been executed directly ( __name__ == "__main__" is True), or imported
  • If a module has executable code out of the special block
    • That code will be run even if the module is imported

print("Hello from find_functions")

def find_first(values, x):

return values.index(x)

if __name__ == "__main__":

print(find_first([1, 2, 3, 1, 2, 3, 1, 2, 3], 2))

5 of 7

Importing code from other modules - 1

  • import module_name

  • Example from test1.py:

import find_functions

print("Hello from test1")

ml = [6, 7, 6, 7, 6, 7]

x = find_functions.find_first(ml, 6)

print(find_functions.MAX)

6 of 7

Importing code from other modules - 2

  • from module_name import item_name

  • Example from test2.py:

from find_functions import find_last

from find_functions import MAX

print("Hello from test2")

ml = [6, 7, 6, 7, 6, 7]

x = find_last(ml, 6)

print(x, MAX)

7 of 7

Importing code from other modules - 3

  • from module_name import function_name as alias

  • Example from test3.py:

import find_functions as ff

from find_functions import MAX as SIXTEENCUBED

print("Hello from test3")

ml = [6, 7, 6, 7, 6, 7]

x = ff.find_middle(ml, 6)

print(x, SIXTEENCUBED)