\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{datamansam} \pdfinfo{ /Title (python-modules-and-packages.pdf) /Creator (Cheatography) /Author (datamansam) /Subject (Python Modules And Packages Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{A3A3A3} \definecolor{LightBackground}{HTML}{F3F3F3} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Python Modules And Packages Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{datamansam} via \textcolor{DarkBackground}{\uline{cheatography.com/139410/cs/29867/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}datamansam \\ \uline{cheatography.com/datamansam} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Published 30th November, 2021.\\ Updated 30th November, 2021.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{3} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Modules}} \tn % Row 0 \SetRowColor{LightBackground} Single Py Files Containing & Python components you have defined (functions, variables, classes, etc.) Runnable code (scripts) \tn % Row Count 5 (+ 5) % Row 1 \SetRowColor{white} Can be: & Executed (python my\_module.py) Imported from a shell or another file \tn % Row Count 9 (+ 4) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{IMPORTING} \tn % Row Count 10 (+ 1) % Row 3 \SetRowColor{white} When you import a module, a new name, 'bound' to the module, is created in the current scope: & import math \{\{nl\}\} x = math.pow(2, 3) \tn % Row Count 15 (+ 5) % Row 4 \SetRowColor{LightBackground} & from math import pow \{\{nl\}\}x = pow(2, 3) \tn % Row Count 17 (+ 2) % Row 5 \SetRowColor{white} 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 * \{\{nl\}\} x = pow(2, 3) \tn % Row Count 23 (+ 6) % Row 6 \SetRowColor{LightBackground} We could also achieve this by importing all objects in the module, but isk creating namespace conflicts: & from math import * \{\{nl\}\} x = pow(2, 3) \tn % Row Count 29 (+ 6) % Row 7 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{} \tn % Row Count 29 (+ 0) % Row 8 \SetRowColor{LightBackground} 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 \tn % Row Count 33 (+ 4) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Modules (cont)}} \tn % Row 9 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{All runnable code in a module is executed at import.} \tn % Row Count 2 (+ 2) % Row 10 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{f you want it to be executed only when you run the file, use the following:} \tn % Row Count 4 (+ 2) % Row 11 \SetRowColor{LightBackground} if \_\_name\_\_ == "\_\_main\_\_": \{\{nl\}\} print("This will be run only if the file is execut ed") & \_\_name\_\_ is a special built-in variable which will automatically be set to "\_\_main\_\_" if the source file is being executed as the main program, rather than being imported. \tn % Row Count 13 (+ 9) % Row 12 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{When importing, Python looks for the module with the same name in:} \tn % Row Count 15 (+ 2) % Row 13 \SetRowColor{LightBackground} The built-in modules & The directories defined in the sys.path list: \tn % Row Count 18 (+ 3) % Row 14 \SetRowColor{white} & The current working directory \{\{nl\}\} The PYTHONPATH list \{\{nl\}\} The default Python directory \tn % Row Count 23 (+ 5) % Row 15 \SetRowColor{LightBackground} You can access this list at runtime and append new paths to it manually: & import sys print(sys.path) \seqsplit{sys.path.append("/path/to/add")} \tn % Row Count 27 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Code to treat Jupyter notebooks as modules}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{import io, os, sys, types \newline % Row Count 1 (+ 1) import nbformat \newline % Row Count 2 (+ 1) from IPython import get\_ipython \newline % Row Count 3 (+ 1) from \seqsplit{IPython.core.interactiveshell} import InteractiveShell \newline % Row Count 5 (+ 2) def find\_notebook(fullname, path=None): \newline % Row Count 6 (+ 1) """find a notebook, given its fully qualified name and an optional path \newline % Row Count 8 (+ 2) This turns "foo.bar" into "foo/bar.ipynb" \newline % Row Count 9 (+ 1) and tries turning "Foo\_Bar" into "Foo Bar" if Foo\_Bar \newline % Row Count 11 (+ 2) does not exist. \newline % Row Count 12 (+ 1) """ \newline % Row Count 13 (+ 1) name = fullname.rsplit('.', 1){[}-1{]} \newline % Row Count 14 (+ 1) if not path: \newline % Row Count 15 (+ 1) path = {[}''{]} \newline % Row Count 16 (+ 1) for d in path: \newline % Row Count 17 (+ 1) nb\_path = os.path.join(d, name + ".ipynb") \newline % Row Count 19 (+ 2) if \seqsplit{os.path.isfile(nb\_path):} \newline % Row Count 20 (+ 1) return nb\_path \newline % Row Count 21 (+ 1) \# let import Notebook\_Name find "Notebook Name.ipynb" \newline % Row Count 23 (+ 2) nb\_path = nb\_path.replace("\_", " ") \newline % Row Count 24 (+ 1) if \seqsplit{os.path.isfile(nb\_path):} \newline % Row Count 25 (+ 1) return nb\_path \newline % Row Count 26 (+ 1) class NotebookLoader(object): \newline % Row Count 27 (+ 1) """Module Loader for IPython Notebooks""" \newline % Row Count 28 (+ 1) def \_\_init\_\_(self, path=None): \newline % Row Count 29 (+ 1) self.shell = \seqsplit{InteractiveShell.instance()} \newline % Row Count 30 (+ 1) } \tn \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Code to treat Jupyter notebooks as modules (cont)}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{ self.path = path \newline % Row Count 1 (+ 1) def load\_module(self, fullname): \newline % Row Count 2 (+ 1) """import a notebook as a module""" \newline % Row Count 3 (+ 1) path = find\_notebook(fullname, self.path) \newline % Row Count 4 (+ 1) print ("importing notebook from \%s" \% path) \newline % Row Count 6 (+ 2) \# load the notebook object \newline % Row Count 7 (+ 1) nb = nbformat.read(path, as\_version=4) \newline % Row Count 8 (+ 1) \# create the module and add it to sys.modules \newline % Row Count 10 (+ 2) \# if name in sys.modules: \newline % Row Count 11 (+ 1) \# return sys.modules{[}name{]} \newline % Row Count 12 (+ 1) mod = \seqsplit{types.ModuleType(fullname)} \newline % Row Count 13 (+ 1) mod.\_\_file\_\_ = path \newline % Row Count 14 (+ 1) mod.\_\_loader\_\_ = self \newline % Row Count 15 (+ 1) mod.\_\_dict\_\_{[}'get\_ipython'{]} = get\_ipython \newline % Row Count 16 (+ 1) sys.modules{[}fullname{]} = mod \newline % Row Count 17 (+ 1) \# extra work to ensure that magics that would affect the user\_ns \newline % Row Count 19 (+ 2) \# actually affect the notebook module's ns \newline % Row Count 21 (+ 2) save\_user\_ns = self.shell.user\_ns \newline % Row Count 22 (+ 1) self.shell.user\_ns = mod.\_\_dict\_\_ \newline % Row Count 23 (+ 1) try: \newline % Row Count 24 (+ 1) for cell in nb.cells: \newline % Row Count 25 (+ 1) if cell.cell\_type == 'code': \newline % Row Count 26 (+ 1) \# transform the input to executable Python \newline % Row Count 28 (+ 2) code = \seqsplit{self.shell.input\_transformer\_manager.transform\_cell(cell.source)} \newline % Row Count 30 (+ 2) } \tn \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Code to treat Jupyter notebooks as modules (cont)}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{ \# run the code in themodule \newline % Row Count 1 (+ 1) exec(code, mod.\_\_dict\_\_) \newline % Row Count 2 (+ 1) finally: \newline % Row Count 3 (+ 1) self.shell.user\_ns = save\_user\_ns \newline % Row Count 4 (+ 1) return mod \newline % Row Count 5 (+ 1) class NotebookFinder(object): \newline % Row Count 6 (+ 1) """Module finder that locates IPython Notebooks""" \newline % Row Count 8 (+ 2) def \_\_init\_\_(self): \newline % Row Count 9 (+ 1) self.loaders = \{\} \newline % Row Count 10 (+ 1) def find\_module(self, fullname, path=None): \newline % Row Count 11 (+ 1) nb\_path = find\_notebook(fullname, path) \newline % Row Count 12 (+ 1) if not nb\_path: \newline % Row Count 13 (+ 1) return \newline % Row Count 14 (+ 1) key = path \newline % Row Count 15 (+ 1) if path: \newline % Row Count 16 (+ 1) \# lists aren't hashable \newline % Row Count 17 (+ 1) key = os.path.sep.join(path) \newline % Row Count 18 (+ 1) if key not in self.loaders: \newline % Row Count 19 (+ 1) self.loaders{[}key{]} = NotebookLoader(path) \newline % Row Count 21 (+ 2) return self.loaders{[}key{]} \newline % Row Count 22 (+ 1) \seqsplit{sys.meta\_path.append(NotebookFinder())}% Row Count 23 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{3.23505 cm} x{1.74195 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Importing ipynb as modules}} \tn % Row 0 \SetRowColor{LightBackground} from NameOfModule import NameOfFunction & from math import pow2 \tn % Row Count 2 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Packages}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Packages are directories that contain modules and/or other packages. This can be a good way to group modules in a hierarchical directory structure.} \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} \_\_init\_\_.py in a package will be executed at import. & Can be used to import nested modules at a higher level of hierarchy \tn % Row Count 7 (+ 4) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{When working with packages, it is recommended to assume code will be run from the top level and use absolute imports from there} \tn % Row Count 10 (+ 3) % Row 3 \SetRowColor{white} Add an extra level of hierarchy and a setup.py file & To install run: pip install my\_package/ (the / is important) \tn % Row Count 13 (+ 3) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Once installed, you can import your module from Python, or run an executable in the shell if you've defined an entrypoint.} \tn % Row Count 16 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}