A Review of Module Basics

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will review the basics of modules in Python. We will learn how to create a module, import a module, and use a module in a Python program.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/scope("`Scope`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/PythonStandardLibraryGroup -.-> python/os_system("`Operating System and System`") python/BasicConceptsGroup -.-> python/python_shell("`Python Shell`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132528{{"`A Review of Module Basics`"}} python/booleans -.-> lab-132528{{"`A Review of Module Basics`"}} python/lists -.-> lab-132528{{"`A Review of Module Basics`"}} python/tuples -.-> lab-132528{{"`A Review of Module Basics`"}} python/function_definition -.-> lab-132528{{"`A Review of Module Basics`"}} python/scope -.-> lab-132528{{"`A Review of Module Basics`"}} python/importing_modules -.-> lab-132528{{"`A Review of Module Basics`"}} python/using_packages -.-> lab-132528{{"`A Review of Module Basics`"}} python/standard_libraries -.-> lab-132528{{"`A Review of Module Basics`"}} python/classes_objects -.-> lab-132528{{"`A Review of Module Basics`"}} python/encapsulation -.-> lab-132528{{"`A Review of Module Basics`"}} python/os_system -.-> lab-132528{{"`A Review of Module Basics`"}} python/python_shell -.-> lab-132528{{"`A Review of Module Basics`"}} python/build_in_functions -.-> lab-132528{{"`A Review of Module Basics`"}} end

Preparation

This exercise is about some of the more tricky details of library modules. Start this exercise by creating a very simple library module:

## simplemod.py

x = 42        ## A global variable

## A simple function
def foo():
    print('x is', x)

## A simple class
class Spam:
    def yow(self):
        print('Yow!')

## A scripting statement
print('Loaded simplemod')

Module Loading and System Path

Try importing the module you just created:

>>> import simplemod
Loaded simplemod
>>> simplemod.foo()
x is 42
>>>

If this failed with an ImportError, your path setting is flaky. Look at the value of sys.path and fix it.

>>> import sys
>>> sys.path
... look at the result ...
>>>

Repeated Module Loading

Make sure you understand that modules are only loaded once. Try a repeated import and notice how you do not see the output from the print function:

>>> import simplemod
>>>

Try changing the value of x and see that a repeated import has no effect.

>>> simplemod.x
42
>>> simplemod.x = 13
>>> simplemod.x
13
>>> import simplemod
>>> simplemod.x
13
>>>

Use importlib.reload() if you want to force a module to reload.

>>> import importlib
>>> importlib.reload(simplemod)
Loaded simplemod
<module 'simplemod' from 'simplemod.py'>
>>> simplemod.x
42
>>>

sys.modules is a dictionary of all loaded modules. Take a look at it, delete your module, and try a repeated import.

>>> sys.modules
... look at output ...
>>> sys.modules['simplemod']
<module 'simplemod' from 'simplemod.py'>
>>> del sys.modules['simplemod']
>>> import simplemod
Loaded simplemod
>>>

from module import

Restart Python and import a selected symbol from a module.

>>> ################ [ RESTART ] ################ >>> from simplemod import foo
Loaded simplemod
>>> foo()
x is 42
>>>

Notice how this loaded the entire module (observe the output of the print function and how the x variable is used).

When you use from, the module object itself is not visible. For example:

>>> simplemod.foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'simplemod' is not defined
>>>

Make sure you understand that when you export things from a module, they are simply name references. For example, try this and explain:

>>> from simplemod import x,foo
>>> x
42
>>> foo()
x is 42
>>> x = 13
>>> foo()
x is 42                   ## !! Please explain
>>> x
13
>>>

Broken reload()

Create an instance:

>>> import simplemod
>>> s = simplemod.Spam()
>>> s.yow()
Yow!
>>>

Now, go to the simplemod.py file and change the implementation of Spam.yow() to the following:

## simplemod.py
...

class Spam:
    def yow(self):
        print('More Yow!')

Now, watch what happens on a reload. Do not restart Python for this part.

>>> importlib.reload(simplemod)
Loaded simplemod
<module 'simplemod' from 'simplemod.py'>
>>> s.yow()
'Yow!'
>>> t = simplemod.Spam()
>>> t.yow()
'More Yow!'
>>>

Notice how you have two instances of Spam, but they're using different implementations of the yow() method. Yes, actually both versions of code are loaded at the same time. You'll find other oddities as well. For example:

>>> s
<simplemod.Spam object at 0x1006940b8>
>>> isinstance(s, simplemod.Spam)
False
>>> isinstance(t, simplemod.Spam)
True
>>>

Bottom line: It's probably best not to rely on reloading for anything important. It might be fine if you're just trying to debug some things (as long as you're aware of its limitations and dangers).

Summary

Congratulations! You have completed the A Review of Module Basics lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like