Preparation#

Reading material#

This weeks covers roughly Chapter 13 of the book WhirlwindTour Of Python, Modules and Packages.

A similar content is covered in Kaggle Tutorial Working with External Libraries.

Copy-and-Run#

Prep 13.1: Importing a Module#

Let’s write a module. Copy the following code into a new Python file and save it as my_module.py in your current working directory (CWD).

def get_coursename():
    return 'Programming'

Now, run the following code from another script, which we will call your main script.

import my_module
print(my_module.get_coursename())

You have just imported a module that you created yourself, and used a function from it.

Let’s get more familiar with modules. Run the following code in your main script.

import my_module
print(type(my_module))

As with everything in Python, a module is an object. Try printing the type of my_module.get_coursename to confirm that the function is also an object.

Let’s try different ways of importing the module. Run the following code in your main script. Run the code below in a main script - either create a new script or modify the existing one.

import my_module as mm
print(mm.get_coursename())

Here you have used an alias mm for the module my_module, so you don’t have to type the full name of the module every time you want to use it. Some modules have a common alias, like np for numpy, but you can choose any alias you like.

Run now the following code in your main script.

from my_module import get_coursename
print(get_coursename())

Here you imported a single function from the module. This is useful when you only need a single function from a module.

Here you imported a single function from the module and gave it an alias.

You will maybe see imports line from my_module import * which imports all functions from the module. This is generally discouraged as you might coincidentally overwrite definitions in your script.

Prep 13.2: More About Importing#

Add the following code to your my_module.py module.

print('This is a print from my_module.py')

Import the module now, and try using the function get_coursename(), just like you did before, using any of the import methods you have learned.

As you can see, the print statement in the module is executed when the module is imported. This is because the module is executed when it is imported.

Now add this line of code to your module.

print('A' + 10)

Try importing the module again and using the function get_coursename(). What happens?

As you can see, the error in the module code prevents the module from being imported.

Remove the faulty line from your module. Instead, add a definition of a small class from the code below.

class NameKeeper():
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return self.name
    def shout(self):
        print(self.name.upper() + '!!!')

Now, run this code in your main script.

import my_module
name_keeper = my_module.NameKeeper('John')
name_keeper.shout()

You have now used a class from a module.

Prep 13.3: The dir Function#

Run this code in your main script.

import my_module
print(dir(my_module))

The dir() function returns all properties of the specified object. For a module, the list returned by dir() will include some special properties, like __name__ and __file__. It will also include all functions, classes and variables defined in the module. Find get_coursename in the list returned by dir(). Find also NameKeeper in the list.

When you wrote a module yourself, you know what functions are in it. But when you import a module that you didn’t write yourself, you might not know what functions are in it. Run the following code.

import math
print(dir(math))

You can see many functions provided by the math module. Let’s try to see what is in the numpy module. Run the following code.

import numpy as np
print(dir(np))

Clearly, the numpy module contains a lot of functions.

As said, dir() takes an object as an argument. Try printing dir(list) and dir(str). This might come handy if you want to check which methods are available for the certain data type.

Prep 13.4: More on Modules#

One of Python’s greatest strengths is its extensive collection of modules and packages (groups of related modules). These allow you to leverage pre-written functionality instead of building everything from scratch, as we’ve done above.

Python modules and packages can be broadly categorized into three types:

  • Built-in modules These are part of the Python standard library and come pre-installed with Python. Examples include math and os, which we have used during this course. The standard library contains dozens of modules for most common tasks.

  • Widely used third-party packages These need to be installed separately but are considered essential in the Python community. Examples include NumPy and Matplotlib, which you worked with last week. Several such modules were installed on your computer during the automated Python installation provided by Python Support. This category includes dozens of popular and well-documented tools.

  • Community contributed modules These are created and shared by Python users and made available through package managers. While these modules can be incredibly useful, their quality may vary. It’s essential to evaluate and select community-contributed modules critically.

Prep 13.5: Where Are Modules?#

Clearly, you can see that the module is not in the current working directory. But you know that you also can import math, which is not in the current working directory. So, where does Python look for modules?

Try running this code.

import sys
print(sys.path)

What you see is a list of directories where Python looks for modules.

More precisely, Python will first search for a module among the built-in modules. If it doesn’t find the module there, it will look in the current working directory. If it doesn’t find it there, it will look in the directories specified in the sys.path list.

Knowing that, consider what would happen if we have a file called math.py in the current working directory? Could you still import the math module? And what if you had a file called numpy.py in the current working directory? Could you still import the numpy module?

Since sys.path is a list, you can append directories to it, if you want Python to look for modules in a specific directory. This is only valid for the current session, and will not permanently change the sys.path list.

Prep 13.6: Installing Packages#

Although installing and managing packages is a necessary part of working with Python, it’s more of an occasional maintenance task than something you’ll do daily. To help you manage your Python environment effectively, Python Support offers guidance on Packages and Environments. It’s worth reviewing this material before making changes to your setup.

Self quiz#

Question 13.1#

Which of the following is not a built-in or widely used module in Python?

Question 13.2#

You have a python file my_file.py with some functions you want to use in another file. Which of the following allows you to do that?

Question 13.3#

You want to use the function my_function from a Python file my_file.py. Which of the following allows you to do that?

Question 13.4#

You imported the math module using import math as m. How would you compute sin(π/8)?

Question 13.5#

You imported NumPy using import numpy as np. What do you expect print(dir(np)) to print?

Question 13.6#

Say you have a file my_file.py with the following content

def my_function(x):
    return x + 1

What will be printed the following code is executed in another file?

import my_file
print(my_file.my_function(5))

Question 13.7#

You have a file my_file.py with the following content

def my_function(x):
    return x + 1
print(x)

What will happen if you import this file using import my_file?

Question 13.8#

You have a file numpy.py in your current working directory. What will happen when you run import numpy as np?

Question 13.9#

What is the difference between import module_name and from module_name import *?

Question 13.10#

You have a python file my_module.py with the following content

class Shout():
    pass

How can you use the Shout class in another file?