Modules and Packages Flashcards
What is a module?
a piece of software that has a specific functionality
How can you write a module in Python?
Modules in Python are simply Python files with a .py extension. The name of the module will be the name of the file. A Python module can have a set of functions, classes or variables defined and implemented.
How do you import modules from other modules?
Using the “import” command
How can you import classes / functions from modules?
Using the “.” (dot) operator. import draw (at the beginning will import the draw module. draw.draw_game(result) will pass the parameter “result” to the draw_game function from the draw module.
Why does a .pyc file appear when importing a module?
A .pyc file appears, which is a compiled Python file. Python compiles files into Python bytecode so that it won’t have to parse the files each time modules are loaded. If a .pyc file exists, it gets loaded instead of the .py file, but this process is transparent to the user.
How can you import all the objects from a module? (2 ways)
from module import * import module
Can you rename a module you are importing? How? (2 ways)
import module as mod import module mod
How does a module initialize?
The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will NOT be loaded twice - so local variables inside the module act as a “singleton” - they are initialized only once.
How can you add a location to where the Python interpreter looks for a python module? (2 ways)
PYTHONPATH=/foo python game.py
This will execute game.py, and will enable the script to load modules from the foo directory as well as the local directory.
sys.path.append(“/foo”)
Another method is the sys.path.append function. You may execute it before running an import command.
How can you look through which functions are implemented in a module? Use urllib as your example
import urllib
dir(urllib)
import urllib
help(urllib.request)
What is the difference between dir() and help()?
dir() will show you all the functions in a module. help() will give you high level information about the module and implementation of the function.
What are Python packages? What MUST each python package contain?
Packages are namespaces which contain multiple packages and modules themselves. Each package in Python is a directory which MUST contain a special file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.
If you have a package named foo with a module named bar, show two ways you can import the module bar.
from foo import bar
import foo.bar