Programming Assignment(PA) 1

  • Take your time to read. I suggest printing out and taking notes.
  • Readiness Quiz
  • Testing and limit of 10 attempts to the autograder
  • You need to test your code thoroughly before using autograder
    • you need to install pytest
    • you need to write a series of tests in test_dice.py

Modules

  • script: .py file where Python program is saved. Intended to be run directly. Can have statements outside of a function.
  • module: Python file for importing into a script or othe modules. It defines functions and can have variables that are intended to be used in other files that import the module
  • Assume a file mymath.py
    • import mymath
    • __name__
      • "main" in mymath.py when not imported
      • "mymath" in mymapth.py when imported
  • import a module, use filename without .py of module file
    • good practice: import statements at the top of the file
    • the code of the module is executed
      • if module imported >1, only executed one time
      • make us of __name__ to determine what is executed
    • use . to access contents of module

Import will execute the module

  • what does that imply?
  • if code outside of function in module, what happends when imported?
  • if code inside of function in module, what happends when imported?
  • function definitions are not executed
  • statements outside of functions are executed the first time the import is performed
  • unintended side effects of the import

Another way to import but different

from module_name import name1, name2 ...

  • namespace is different
    • imported names are in the global namespace, that is, copies are made
  • do not need the .
from math import pi
print(pi) # instead math.pi

Rename a module importing

import math as m
print(m.pi)

There is always more to learn ...

  • next time

more on import and modules

  • module contents are in a separte namespace
  • namespace
    • internally a dictionary
    • key => object name
    • value => the object itself
    • four types of namespace
      • built-n; global; enclosing; local
  • scope
    • namespace for global
    • namespace for each local
  • dir()
    • list of defined names in a namespace
    • dir(object) objectt can be imported module

More about namespace

loading a module:
- a module object is created and inserted in sys.modules
- module object is a namespace that has definitions from the module
- adds module object to the global namespace
- dir() or dir(module_name)
- the code of the module is executed
- if module imported >1, only executed one
- a module object contains the definitions from the module

  • packages: collection of related modules that provide some functionality. Will contain __init__ to indicate a package.
  • library: bundle of code, can have 100s of modules
  • Python standard library: comes with your installation of Python