πŸ“Modules and Packages#

In Python tools are built around modules that perform operations

Modularity allows the isolation of code to simplify programming

Built-in Functions#

Python contains many built in functions

Finding a DataType#

type("Drexel Engineering")
str

You can find more built-in functions

Built-in Modules#

The base package of python contains built-in modules. These have to be imported before they can be used.

You import modules using

import <Module Name>

Random#

We can use random to sample a random integer. This would make a 6-sided die.

import random
dice = random.randint(1,6)
print(dice)
4

You can view everything included in the standard library here

External Packages#

There are many additional packages. Anyone in the world can make a package. Most packages are distributed using the Python Package Index (PyPI).

You can install packages using package managers:

pip install <package name>

or

conda install <package name>

Importing Matplotlib#

A common plotting package in Python is matplotlib, we can import and use matplotlib.

Note

Usually when you download python distributions they will contain many of the common packages. We have installed all the packages you need for the course on the JupyterHub.

Syntax#

from {package name} import {module}

from {package name} import {module} as {name}</code></pre>
import matplotlib.pyplot as plt
plt.plot([0,1,2,3,4,5],'-sk')
[<matplotlib.lines.Line2D at 0x7f878629f670>]
../../_images/f93a4a596e70f00c77d81864576af8c59e683f33fa7ff8f7f6cd6ca895c2121a.png

Submodules#

Many modules contain submodules. These can be accessed by calling <module>.<submodule>

Tip

If you type a module name. you can use tab to discover the available submodules

plt.

Making Your Own Modules#

You can make your own modules by building a function

    def module_name(input):
        a = 'line 1'
        b = input
        return a, b
def Drexel(college):
    return "Drexel " + college
print(Drexel("engineering"))
Drexel engineering
print(Drexel("Arts and Sciences"))
Drexel Arts and Sciences

Loading Modules from Files#

You can load modules from files

This is a script that writes a file

%%writefile drexel.py

def Drexel(name):
    return "I, " + name + " am a Drexel Dragon"
Overwriting drexel.py
import drexel as Drexel
Drexel.Drexel("Jay")
'I, Jay am a Drexel Dragon'

Reloading Modules#

Once you load a module if it changes you need to reload it.

Changing the module

%%writefile drexel.py

def Drexel(name):
    return "I, " + name + " am a Drexel Dragon Engineer!!"
Overwriting drexel.py

Using importlib.reload to reload the module.

import importlib
importlib.reload(Drexel)
<module 'drexel' from '/usr/src/app/jupyterbook/week1/lecture1/drexel.py'>
Drexel.Drexel("Jay")
'I, Jay am a Drexel Dragon Engineer!!'

Existing Python Packages#

from IPython.display import IFrame
IFrame('https://wiki.python.org/moin/UsefulModules', width=800, height=1200)