MCS 260 Fall 2021
Emily Dumas
A complex Python program usually has many lines.
Keeping them in one file is quite limiting. Very long source files are hard to navigate and understand.
Modules are Python's solution. They let you spread code across multiple files.
We discussed a number a modules that are part of Python's standard library, meaning they are always available.
e.g. sys, os, math, random, json, csv
You use import MODULENAME
to make available, then MODULENAME.funcname(...args...)
.
import os
if os.path.exists("out.dat"):
print("Error: out.dat already exists")
exit(1)
import foo
will look for a module named "foo" in the current directory and several other places. The list of places is stored in sys.path
.
For example if foo.py
exists in the current directory, it will be imported by this command.
Functions and variables from the module are made available with the module name as a prefix, e.g. doit()
becomes foo.doit()
.
Code in the module outside any function is executed. Usually, files designed to be used as modules have no code other than functions and global variables.
If you want to, it is possible to import a few functions from a module into the global namespace, i.e. so the module name need not be used when calling them.
import random
print("Random digit: ",random.randint(0,9))
If you want to, it is possible to import a few functions from a module into the global namespace, i.e. so the module name need not be used when calling them.
from random import randint
print("Random digit: ",randint(0,9))
from module import name
Import multiple names to global namespace:
from module import name0, name1, name2
Import all names to global namespace:
from module import *
import foo
is almost always better thanfrom foo import ...
You are not allowed to use from foo import ...
in code submitted to MCS 260 assignments.
It is convenient to write programs that do something when run on their own, but which only define functions when imported. This makes it easier to test functions in the REPL, for example.
# no_main_wrap.py
# Importing this will run the main loop
def f(x):
"""polynomial function"""
return 2.0*x**3 - 3.0*x**2
# Main loop
for i in range(11):
t = i/10
print("f({}) = {}".format(t,f(t)))
# main_wrap.py
# Importing this will not run anything
def f(x):
"""polynomial function"""
return 2.0*x**3 - 3.0*x**2
def main():
# Main loop
for i in range(11):
t = i/10
print("f({}) = {}".format(t,f(t)))
if __name__=="__main__":
# We are the main program, not an import
main()