jupyter notebooks intro

This exercise is intended to introduce the concept on ipython notebooks, why we use them, and how the interact with other python files.

WHY?

The markdown with embedded code concept is available for a few languages (R and python among them) but it is a pretty foreign concept for most programmers. So why do we use them? Here are a couple reasons

Explaining a concept

This is a great use of the notebook format. You can have beautiful markdown with embedded, runnable code samples. Well formatted text with hands on code demos can be very valuable. In this notebook I use the format to explain the python module system.

Runnable documentation

In this class we will also use the format to call functions from libraries we write. It makes it easy to explain what your function call is doing and provide a runnable example so people can see it in action.

There are other reasons to use them, but they essentially boil down to being able to use text to explain code or using code to give more understanding to some text that was written.

simple imports

In python each file is a module. We can import a .py file using the import keyword followed by the name of the file (without the file extension)


In [ ]:
import sample

sample.f1()

module alias

Sometimes, we don't want to use the full name of a module every time we use the module. We can alias the module to some arbitrary name


In [ ]:
import sample2 as s

s.f2()

Import specific pieces

We can import just one function (or class or variable) with the following syntax. If we have a few things we want to import from a module we can do

from module import thing1, thing2, thing3 ...


In [ ]:
from sample3 import f3

f3()

Import everything from module

Careful with this. It is generally frowned upon because it pollutes the namespace (higher likelihood of two things having the same name)


In [ ]:
from sample import *

f1()

Nested modules

If you have subdirectory which contains other python files you can import nested modules with the following syntax.


In [ ]:
import nest.sample4

nest.sample4.f4()

Good idea to alias long names

This is especially imported for nested modules. Your time is valuable. Writing long names is a waste of time. Aliases can help.


In [ ]:
import nest.sample4 as s

s.f4()