Show Menu
Cheatography

Python Modules And Packages by

Modules

Single Py Files Containing
Python components you have defined (funct­ions, variables, classes, etc.) Runnable code (scripts)
Can be:
Executed (python my_mod­ule.py) Imported from a shell or another file
IMPORTING
When you import a module, a new name, 'bound' to the module, is created in the current scope:
import math
x = math.p­ow(2, 3)
 
from math import pow
x = pow(2, 3)
We can also import a specific function from the module, and so now we don't need to specify the module name
from math import *
x = pow(2, 3)
We could also achieve this by importing all objects in the module, but isk creating namespace conflicts:
from math import *
x = pow(2, 3)
 
We can import a module under an alias to bind it to a name of our choice:
import pandas as pd import seaborn as sns
All runnable code in a module is executed at import.
f you want it to be executed only when you run the file, use the following:
if __name__ == "­__m­ain­__":
print(­"This will be run only if the file is execut ed")
__name__ is a special built-in variable which will automa­tically be set to "­__m­ain­__" if the source file is being executed as the main program, rather than being imported.
When importing, Python looks for the module with the same name in:
The built-in modules
The direct­ories defined in the sys.path list:
 
The current working directory
The PYTHONPATH list
The default Python directory
You can access this list at runtime and append new paths to it manually:
import sys print(­sys.path) sys.pa­th.a­pp­end­("/p­ath­/to­/ad­d")
 

Code to treat Jupyter notebooks as modules

import io, os, sys, types
import nbformat

from IPython import get_ip­ython
from IPytho­n.c­ore.in­ter­act­ive­shell import Intera­cti­veShell


def find_n­ote­boo­k(f­ull­name, path=N­one):
"­"­"find a notebook, given its fully qualified name and an optional path

This turns "­foo.ba­r" into "­foo­/ba­r.i­pyn­b"
and tries turning "­Foo­_Ba­r" into "Foo Bar" if Foo_Bar
does not exist.
"­"­"
name = fullna­me.r­sp­lit­('.', 1)[-1]
if not path:
path = ['']
for d in path:
nb_path = os.pat­h.j­oin(d, name + ".ip­ynb­")
if os.pat­h.i­sfi­le(­nb_­path):
return nb_path
# let import Notebo­ok_Name find "­Not­ebook Name.i­pyn­b"
nb_path = nb_pat­h.r­epl­ace­("_", " ")
if os.pat­h.i­sfi­le(­nb_­path):
return nb_path


class Notebo­okL­oad­er(­obj­ect):
"­"­"­Module Loader for IPython Notebo­oks­"­"­"
def __init­__(­self, path=N­one):
self.shell = Intera­cti­veS­hel­l.i­nst­ance()
self.path = path

def load_m­odu­le(­self, fullname):
"­"­"­import a notebook as a module­"­"­"
path = find_n­ote­boo­k(f­ull­name, self.path)

print ("im­porting notebook from %s" % path)

# load the notebook object
nb = nbform­at.r­ea­d(path, as_ver­sion=4)


# create the module and add it to sys.mo­dules
# if name in sys.mo­dules:
# return sys.mo­dul­es[­name]
mod = types.M­od­ule­Typ­e(f­ull­name)
mod.__­file__ = path
mod.__­loa­der__ = self
mod.__­dic­t__­['g­et_­ipy­thon'] = get_ip­ython
sys.mo­dul­es[­ful­lname] = mod

# extra work to ensure that magics that would affect the user_ns
# actually affect the notebook module's ns
save_u­ser_ns = self.s­hel­l.u­ser_ns
self.s­hel­l.u­ser_ns = mod.__­dict__

try:
for cell in nb.cells:
if cell.c­ell­_type == 'code':
# transform the input to executable Python
code = self.s­hel­l.i­npu­t_t­ran­sfo­rme­r_m­ana­ger.tr­ans­for­m_c­ell­(ce­ll.s­ource)
# run the code in themodule
exec(code, mod.__­dict__)
finally:
self.s­hel­l.u­ser_ns = save_u­ser_ns
return mod


class Notebo­okF­ind­er(­obj­ect):
"­"­"­Module finder that locates IPython Notebo­oks­"­"­"
def __init­__(­self):
self.l­oaders = {}

def find_m­odu­le(­self, fullname, path=N­one):
nb_path = find_n­ote­boo­k(f­ull­name, path)
if not nb_path:
return

key = path
if path:
# lists aren't hashable
key = os.pat­h.s­ep.j­oi­n(path)

if key not in self.l­oaders:
self.l­oad­ers­[key] = Notebo­okL­oad­er(­path)
return self.l­oad­ers­[key]


sys.me­ta_­pat­h.a­ppe­nd(­Not­ebo­okF­ind­er())

Importing ipynb as modules

from NameOf­Module import NameOf­Fun­ction
from math import pow2
 

Packages

Packages are direct­ories that contain modules and/or other packages. This can be a good way to group modules in a hierar­chical directory structure.
__init­__.py in a package will be executed at import.
Can be used to import nested modules at a higher level of hierarchy
When working with packages, it is recomm­ended to assume code will be run from the top level and use absolute imports from there
Add an extra level of hierarchy and a setup.py file
To install run: pip install my_pac­kage/ (the / is important)
Once installed, you can import your module from Python, or run an executable in the shell if you've defined an entryp­oint.
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          More Cheat Sheets by datamansam