10  Importing Code

Every Python installation has a number of modules that come by default. They are called collectively the “Python Standard Library” or “built-in” modules.

Even though these modules are available in our computer, we cannot directly use them, we need to import them into our current namespace to actually use them.

For example, if we try to use the module pathlib, we get this NameError

pathlib
NameError: name 'pathlib' is not defined

That means that the word pathlib is unknown in this context. Let’s bring it in:

import pathlib

Now we can use it:

pathlib.Path(".")
PosixPath('.')

We can also import only specific parts of the module:

from pathlib import Path

It is also possible to alias these imported names using the keyword as:

import pathlib as pl
pl.Path(".")
PosixPath('.')

10.1 Script vs. exportable code

A Python module (any .py file) might contain code that we want to run (for example as a one-off script) along code that we only want to use somewhere else.
For example, we might have a bunch of code like this in a file:

We can isolate the part of the code that we want to run as a script with this trick.

# data.py

def download(url):
    ...
def process(data):
    ... 
def plot(data):
    ...
     
if __name__ == "__main__":
    print("I am running as a script")    
    def script_func():
        ...
    

10.2 Exercises

  1. Copy the content of the code above into a file data.py and run it
  2. Create another file called analysis.py right next to data.py (in the same directory)
  3. Inside analysis.py import download from data.py and run analysis.py
  4. Inside analysis.py import script_func from data.py and run analysis.py. Do you understand what happens?