Using script files#

Attention

Finnish university students are encouraged to use the CSC Notebooks platform.
CSC badge

Others can follow the lesson and fill in their student notebooks using Binder.
Binder badge

In this lesson we introduce you to how to put your functions in a script file for convenient use in notebooks or other script files.

An introduction to script files#

Up to this point we have been keeping our Python code and Markdown comments in a single Jupyter notebook document. This is great, but there are some cases, like when you have long Python code blocks or a set of functions used in many notebooks, in which you may want to have Python code in a separate document to make sure your Jupyter notebook is easy to read (and use). An alternative to typing in all of the commands you would like to run is the list them in a Python script (ohjelma) file. A Python script file is simply a file containing a list of the commands you would like to run, normally with one command per line, and formatted in the same way as if you were to type them in. Python script files traditionally use the .py file extension in their names.

The general concept of a .py script file#

Because a Python script file is simply a list of commands that you might otherwise type into a Python cell in a Jupyter notebook or a Python console, we can quite easily create a basic script file and test things out.

Getting started#

First, we need to create a new text file by clicking on File -> New -> Python File in the JupyterLab menu bar.

Creating a new Python file in JupyterLab.

This will create a new tab in your JupyterLab window that should look something like that below, a blank slate.

Our new Python file in JupyterLab.

Start by copying and pasting the text below into your new text file editor panel.

def celsius_to_fahr(temp_celsius):
    return 9/5 * temp_celsius + 32

Renaming our Python file#

Python scripts are just regular text files with the .py file extension that will identify them as source code for Python in JupyterLab. By default, new Python files will be called untitled.py. You can rename the file by right clicking on the tab titled untitled.py and renaming it as temp_converter.py.

Renaming a Python file in JupyterLab.

Changing the file name in JupyterLab.

Note

Be sure to save your temp_converter.py file after making your changes.

We’ll return later to some best practices for writing script files, but for now let’s continue with how to use our functions saved in the Python file we just created.

Saving and loading functions#

Functions such as the ones we just created can also be saved in a script file and called from Jupyter notebooks. In fact, quite often it is useful to create a dedicated function library for functions that you use frequently, when doing data analysis, for example. Basically this is done by listing useful functions in a single .py file from which you can then import and use them whenever needed.

Saving functions in a script file#

Basically, we’ve just seen how to save some functions to a script file. Let’s now add the other functions we had been using to our script. Simply copy and paste the text below into your temp_converter.py file leaving two blank lines between each function, as suggested in the PEP 8 guidelines.

def kelvins_to_celsius(temp_kelvins):
    return temp_kelvins - 273.15


def kelvins_to_fahr(temp_kelvins):
    temp_celsius = kelvins_to_celsius(temp_kelvins)
    temp_fahr = celsius_to_fahr(temp_celsius)
    return temp_fahr

Don’t forget to save your changes!

Calling functions from a script file#

Now that we have saved our temperature conversion functions into a script file we can start using them.

Making sure we’re in the right working directory#

Hopefully you have saved your temp_converter.py file in the same location as this Jupyter notebook (script-files.ipynb). If so, that’s good, but we need to do one more thing to be able to start working with it. We need to change the working directory in JupyterLab to be the one where the temp_converter.py exists.

First, we can check where we are working currently using an IPython magic command called %ls. %ls allows us to see the files located in the directory where we are currently working. You can run the %ls command in the cell below to see which files are in the current working directory.

%ls
functions.ipynb              img/           script-files.ipynb
gcp-4-writing-scripts.ipynb  modules.ipynb

If your output from the %ls command looks like

functions.ipynb              modules.ipynb
gcp-4-writing-scripts.ipynb  script-files.ipynb
img/                         temp_converter.py

then you are all set to continue. Otherwise, you should follow the steps below to make sure you are working in the correct directory.

CSC notebooks users#

Those using the CSC notebooks might see something like

my-work/  shared/

In this case you will need to change directories to the one containing the temp_converter.py file. You can do this by typing

%cd my-work/notebooks/L4/

Binder users#

If you are using Binder, you may see

L1/  L2/  L3/  L4/  README.md  requirements.txt

and you will need to change directories. To do this you should type the following to change into the directory containing the temp_converter.py file.

%cd L4/

Confirming we are in the correct directory#

At this point we can run the %ls command once more to make sure we’re in the correct directory. You should see the temp_converter.py file in the list of files and directories that are output.

%ls
functions.ipynb              img/           script-files.ipynb
gcp-4-writing-scripts.ipynb  modules.ipynb

Importing our script functions#

Let’s now import our celsius_to_fahr() function from the other script by adding a specific import statement in the Python cell below: from temp_converter import celsius_to_fahr

# DO NOT RUN THIS CELL
# This cell is only needed for generating the course web page
%cd ../../_static/L4/
/home/docs/checkouts/readthedocs.org/user_builds/geo-python-site/checkouts/latest/source/_static/L4
from temp_converter import celsius_to_fahr

Using our script functions#

Let’s also use the function so that we can see that it is working. We can print the temperature in Fahrenheit at which water freezes using our celsius_to_fahr() function in the cell below.

print(f"The freezing point of water in Fahrenheit is {celsius_to_fahr(0)}")
The freezing point of water in Fahrenheit is 32.0

You should get following output:

The freezing point of water in Fahrenheit is 32.0

Importing multiple functions#

It is also possible to import more functions at the same time by listing and separating them with a comma.

from my_script import func1, func2, func3

Importing all functions from a script#

Sometimes it is useful to import the whole script and all of its functions at once. Let’s use a different import statement and test that all functions work. This time we can type import temp_converter as tc.

import temp_converter as tc

Just like the examples we have seen earlier with the math library, such as using math.sin(), we can now use our functions such as tc.celsius_to_fahr(). In the cells below, test our functions as they were used above by printing the freezing point of water in Fahrenheit, absolute zero in Celsius, and absolute zero in Fahrenheit.

print(f"The freezing point of water in Fahrenheit is {tc.celsius_to_fahr(0)}")
The freezing point of water in Fahrenheit is 32.0
print(f"Absolute zero in Celsius is {tc.kelvins_to_celsius(temp_kelvins=0)}")
Absolute zero in Celsius is -273.15
print(f"Absolute zero in Fahrenheit is {tc.kelvins_to_fahr(temp_kelvins=0)}")
Absolute zero in Fahrenheit is -459.66999999999996

Temperature calculator (optional, advanced topic)#

So far our functions have had only one parameter, but it is also possible to define a function with multiple parameters. Let’s now make a simple temp_calculator function that accepts temperatures in Kelvins and returns values in either degrees Celsius or degrees Fahrenheit. The new function will have two parameters:

  • temp_k = The parameter for passing temperature in Kelvins

  • convert_to = The parameter that determines whether to output should be in Celsius or in Fahrenheit (using the letters C or F accordingly)

Defining the function#

Let’s start defining our function by giving it a name and setting the parameters.

def temp_calculator(temp_k, convert_to):

Adding some conditional statements#

Next, we need to add conditional statements that check whether the desired output temperature should be in Celsius or Fahrenheit, and then call the corresponding function that was imported from the temp_converter.py file.

def temp_calculator(temp_k, convert_to):
    # Check if user wants the temperature in Celsius
    if convert_to == "C":
        # Convert the value to Celsius using the dedicated function for the task that we imported from another script
        converted_temp = kelvins_to_celsius(temp_kelvins=temp_k)
    elif convert_to == "F":
        # Convert the value to Fahrenheit using the dedicated function for the task that we imported from another script
        converted_temp = kelvins_to_fahr(temp_kelvins=temp_k)

Returning the result#

Next, we need to add a return statement so that our function sends back the value that we are interested in.

def temp_calculator(temp_k, convert_to):
    # Check if user wants the temperature in Celsius
    if convert_to == "C":
        # Convert the value to Celsius using the dedicated function for the task that we imported from another script
        converted_temp = kelvins_to_celsius(temp_kelvins=temp_k)
    elif convert_to == "F":
        # Convert the value to Fahrenheit using the dedicated function for the task that we imported from another script
        converted_temp = kelvins_to_fahr(temp_kelvins=temp_k)
    # Return the result
    return converted_temp

Adding a docstring#

Finally, since we want to be good programmers, we should add a short docstring at the beginning of our function that tells what the function does and how the parameters work.

def temp_calculator(temp_k, convert_to):
    """
    Function for converting temperature in Kelvins to Celsius or Fahrenheit.

    Parameters
    ----------
    temp_k: <numerical>
        Temperature in Kelvins
    convert_to: <str>
        Target temperature that can be either Celsius ('C') or Fahrenheit ('F'). Supported values: 'C' | 'F'

    Returns
    -------
    <float>
        Converted temperature.
    """

    # Check if user wants the temperature in Celsius
    if convert_to == "C":
        # Convert the value to Celsius using the dedicated function for the task that we imported from another script
        converted_temp = kelvins_to_celsius(temp_kelvins=temp_k)
    elif convert_to == "F":
        # Convert the value to Fahrenheit using the dedicated function for the task that we imported from another script
        converted_temp = kelvins_to_fahr(temp_kelvins=temp_k)
    # Return the result
    return converted_temp

Testing the new function#

That’s it! Now we have a temperature calculator that has a simple control for the user where they can change the output using the convert_to parameter. Now as we added the short docstring in the beginning of the function we can use the help() function in Python to find out how our function should be used. Run the Python cell below and then try running help(temp_calculator).

Attention

Reloading modules from within a Jupyter notebook is a bit of a pain. The easiest option is to restart the IPython kernel by going to Kernel -> Restart kernel…. Note that this will delete all variables currently stored in memory in the Jupyter notebook you’re using, so you may need to re-run some cells.

help(tc.temp_calculator)
Help on function temp_calculator in module temp_converter:

temp_calculator(temp_k, convert_to)
    Function for converting temperature in Kelvins to Celsius or Fahrenheit.
    
    Parameters
    ----------
    temp_k: <numerical>
        Temperature in Kelvins
    convert_to: <str>
        Target temperature that can be either Celsius ('C') or Fahrenheit ('F'). Supported values: 'C' | 'F'
    
    Returns
    -------
    <float>
        Converted temperature.

Using the temp_calculator function#

Let’s use it.

temp_kelvin = 30
temperature_c = tc.temp_calculator(temp_k=temp_kelvin, convert_to="C")
print(f"Temperature {temp_kelvin} in Kelvins is {temperature_c} in Celsius")
Temperature 30 in Kelvins is -243.14999999999998 in Celsius