9. Modules and Packages Flashcards
What extension does a module have>
.py
How is a module accessed?
Use the import command. Normally at the top of the file.
If we want to import the math module, we simply import the name of the module:
# import the library import math
What two functions are helpful when exploring modules?
dir()
help()
The dir() function does what?
We can look for which functions are implemented in each module by using the dir function:
print(dir(math))
[‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’, ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘pi’, ‘pow’, ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’]
What does the help() function do?
we can read about a method using the help function, inside the Python interpreter:
help(math.ceil)
Help on built-in function ceil in module math:
ceil(…)
ceil(x)
Return the ceiling of x as an Integral. This is the smallest integer >= x.
How do you create a module?
Writing Python modules is very simple. To create a module of your own, simply create a new .py file with the module name, and then import it using the Python file name (without the .py extension) using the import command.
What is a package?
Packages are name-spaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.
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 we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the init.py file inside the foo directory.
What does importing a module look like?
To use the module bar, we can import it in two ways:
# Just an example, this won't work import foo.bar
# OR could do it this way from foo import bar