CODE WITH MARTIN

14. Modules


Overview

We're finally going to learn what that 'import' statement really means that sometimes appears at the top of our example source code...

When we write a lot of Python code, its a good idea to split things up in to separate code files. If you have a single Python file with hundreds upon hundreds of lines, that's going to be a maintenance problem for you at some point in the future.

When we put Python code in to other files, we call it a module. Things like functions, classes and variables inside other files can be accessed by importing them.

Importing Modules

Let's take a look at a snippet of code that we used in the guessing game chapter:

import random

number = random.randint(1, 10)

print(number)

The import statement on line 1 tells Python that we want to use code inside a file named 'random'. When we ask Python to import a file it first looks to see if you have that file in the folder where your source code file is.

I know what you're probably thinking. That file obviously doesn't exist in the folder where your source code file is. However, it does exist in a folder where Python is installed on your machine. There are a few folders where Python looks for files when you try to import them.

Python comes with over a hundred modules that all live in the Python installation folder. It has modules for things like accessing files and folders, working with date and time, accessing the internet, working with specific files like compressed ZIP files or data in CSV files, and so much more.

If you're feeling curious, you can see a complete list of modules at the Python online documentation located here: Python Library Documentation

Back to the example code above, the 'random' module that we are importing is part of the Python standard library of modules and it helps us generate random numbers. On line 3, you'll notice how we use the name of the module that we imported, followed by the dot operator '.' and then a function named 'randint' which we call and assign the return value to the variable 'number'.

The function 'randint' is defined in the 'random' module. Using the dot operator after the module name, we are able to call that function inside the imported module.

Import Name

When we import a module from a specific filename, we can use a different name for it to make it easier to use. Here's an example:

import random as r

number = r.randint(1, 10)

print(number)

You'll notice on line 1 how we've now extended the import statement to use 'as r'. The 'as' keyword lets us rename the module, and the letter 'r' is what we've renamed it to. On line 3, we then use the renamed module name 'r' to access the 'randint' function in the module. Typing 'r' is much easier than typing the full module name 'random'.

You can rename a module to any word you like, as long as it doesn't clash with any defined variable, function, or class names that you've defined in your source code.

Import Specifics

There is one more style of importing things from a module and it's best we show it off starting with some code:

from random import randint

number = randint(1, 10)

print(number)

Line 1 now starts with the 'from' keyword, followed by the name of the module 'random'. We then have the 'import' keyword followed by the name of something specific we want to import, which in this case, is the function named 'randint'.

On line 3, we can now use the 'randint' function without specifying the module name at all. This is because we imported the function name specifically using the 'from' statement on line 1.

This is helpful for when you know there is only something specific you want to import from a module and you don't really need to import everything from the module.

Creating Your Own Module

To demonstrate creating your own module, you'll need two files. Create a new file named 'msg.py' and in there, place the following code:

def say_hello():
    print("Hello there.")

Now create another file in the same folder as 'msg.py', named 'main.py'. Add the following code to this new file:

import msg

msg.say_hello()

Now if you run the 'main.py' file in Visual Studio Code, you will see the printed statement 'Hello there.' in the terminal output. Just as we explained earlier, the import statement on line 1 is letting you access the code contained in that file.

By putting code in separate files, you're now able to re-use modules in other projects or share your modules with other people. A nice habit with some Python developers is if you are creating classes, its nice to put each class in its own file.

Python Packages

Out on the internet, there is a web-site named the Python Package Index hosted at https://pypi.org. It hosts hundreds of thousands of Python modules in what we call packages. All of these packages were created by someone or a company writing their own Python code and publishing their code as a package to that web-site.

If there is something you can imagine doing with Python, someone probably has created a package for it. For example, thinking of writing a web-site with Python? You can do that with a package named 'Django'. How about a 2D or 3D game? There's 'Pygame'. How about reading and sending tweets on Twitter from Python code? Again, there's a package named 'twitter' for that too.

The default modules that are installed as part of Python will only take you so far. At some point, you will want to use a package for doing more fun things with Python. So it's important that we know how to install these packages and use them.

Installing Packages

Packages can be installed using the terminal window in Visual Studio Code. If you don't see it at the bottom, you can open it from the 'Terminal' menu at the top, and then choosing 'New Terminal'.

Type the following three words in to the terminal and hit enter:

pip install requests

You should see some text in the terminal ending with something like 'Successfully installed...'. If you see this, great. If you see some red text with the message 'The term 'pip' is not recognized...', then you'll need to head back to the 'Setup' chapter and reinstall Python.

The command 'pip' that you've typed is the name of the utility that handles installing packages for us from the index web-site. The package we installed is named 'requests'. This package lets us download web pages from the internet and communicate with web sites. Its really easy to use so serves as a good example for us to try.

To test if we installed the package correctly, create a new Python code file with the following code inside:

import requests

r = requests.get("https://www.google.com")

print(r.status_code)

When you run this, you should see the text '200' in the terminal output. This tells us that we successfully used the package that we installed.

If you see the error text 'ImportError: No module name 'requests'', it means that Python can't find the installed package. I suggest you go back to the install step and carefully follow installing the package again.

Uninstalling Packages

To uninstall a package, use the following pip command in the terminal:

pip uninstall requests

After running the command, you will need to type 'y' and hit enter to let the uninstall complete.

Upgrading Packages

Sometimes you'll find you'll want to update a package if a new version of it is released. Use the following pip command in the terminal to update packages:

pip install requests --upgrade

It's the same as how we install a package but with the extra '--upgrade' text at the end.

What We Learned

Congratulations learning about modules and packages. The world of programming is now truly at your finger tips!