Modules
Contents
1.4.5. Modules#
Simply put, a file containing a Python script is called a module. It allow us to separate a code base into multiple files.
We can import
a module to get access to its functions and variables.
%%file fibonacci.py
# Fibonacci numbers module
def fib_print(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
Overwriting fibonacci.py
import fibonacci
fibonacci.fib_print(10)
fibonacci.fib(10)
0 1 1 2 3 5 8
[0, 1, 1, 2, 3, 5, 8]
1.4.5.1. More on Modules#
It is possible to directly import a function or variable from a module.
from fibonacci import (
fib_print,
fib,
)
fibonacci.fib_print(10)
fibonacci.fib(10)
0 1 1 2 3 5 8
[0, 1, 1, 2, 3, 5, 8]
During import, the as
allows to bound a module to a different name in the local namespace.
import fibonacci as fib
fib.fib(10)
[0, 1, 1, 2, 3, 5, 8]
Both variations shown above can be used together.
from fibonacci import fib as fibonacci
fibonacci(10)
[0, 1, 1, 2, 3, 5, 8]
1.4.5.2. Executing modules as scripts#
Running a Python module with
python [filename] <arguments>
executes the code in the module, similarly to importing it, but sets the __name__
to "__main__"
.
Therefore, we can modify the module to allow some code execution when called as a script using:
if __name__ == "__main__":
pass
%%file fibonacci.py
# Fibonacci numbers module
def fib_print(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
if __name__ == "__main__":
import sys
fib_print(int(sys.argv[1]))
Overwriting fibonacci.py
Executing the module as a script will now run the fib_print
function with the given argument.
! python fibonacci.py 10
0 1 1 2 3 5 8
However, importing the module will not execute the fib_print
function.
import fibonacci
1.4.5.3. Packages#
Python packages are a dotted notation to structure module within directories.
For example, a module ./A/B.py
would be imported with import A.B
.
# Importing the `path` module, from the std lib `os`.
import os.path