Python: Create, Import, and Use a Module

Today we are going to cover what I consider a flaw in the iPython Notebook environment. Code you write cannot be imported into another program like you can using just a standard Python compiler. At least it cannot under its native .ipynb format.

There is a work around though. Starting jupyter notebooks up with the –script command results in your notebook being saved as both a ipynb file and a .py file. And .py is what we are looking for.

pyModu

note ‘–script‘ is being deprecated in favor of nbconvert. But as of this moment it still works and will work on older versions you have downloaded as well.

Create a Module

I am going to create a little module call add2. This module contains 3 simple functions: sqr2, sub2, and add2

pyModu1

You can see that now along with my add2.ipynb file, I have a add2.py file.

pyModu2

In my instance, my iPython notebooks are stored under my user directory. If you are not sure where you notebooks are, you can use the pwd command (print working directory)

pyModu3.jpg

** note the double \\ are due to a formatting function in Python. \ is a break command that can be used for many purposes. Example \t means to insert a tab.

pyModu4.jpg

So effectively you have to use \\ if you want a \ in Python, making my working directory C:\Users\Benjamin  

Import the Module

Now if I open up a new notebook and try using the functions I have just created, I will error out.

pyModu5.jpg

So, what I need to do is import add2, then I can start calling on the functions I created in add2

pyModu6


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

Please Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s