Python Modules Tutorial
In this tutorial we learn how to create external code libraries in Python, also known as modules. We cover how to create modules, import them or specific code inside them and how to reload a module at runtime.
What is a module?
A module in Python can be defined as an external code library. A separate file containing its own data containers, functions and classes, to further help us break up and organize our code.
Any file with the .py extension can be a module, which can be imported into any other Python file.
When a module is imported, everything inside the module file is essentially copied into main file and can be accessed with dot notation.
How to create a module
As we’ve mentioned, any .py file can be a module. So let’s create one for this lesson.
- Create a new file in your IDE and name it include.py
Or, in PyCharm, right-click on the project folder in the Explorer pane, select New > Python File and name it include.
Next, in the new file write a simple Python variable with a value.
message = "Hello World"
How to import a whole module
The import statement is used to import all the code from the module into another .py file.
We can import and use the functionality of any .py file into any other .py file.
import module_1, module_2, module_3, ...
import include # access code from imported file print(include.message)
In the example above we import the include file and then access it by specifying the file name, followed by a dot operator and the data-container / function / class we want to access.
How to import specific code from within a module
The from import statement allows us to pick a data container / function / class from a module and only import that.
from module_name import item1, item2, item3, ...
# not accessed message = "Hello World" # accessed greeting = "Hello there"
from include import greeting # access code from imported file print(greeting)
Because we don’t import the whole module, we don’t need to specify the module name when we access the item from the include.py file.
We can also use the from import statement to include a full module with a *.
from include import * # access code from imported file print(greeting) print(message)
In the example above we use the * to indicate we want to import everything. We then have access to both variables and not just the greeting variable.
It’s always better to use the from import if we know in advance which items we want to import from the module. Our code is lighter because we don’t import anything we don’t need.
How to rename a module
When we import a whole module we can create an alias for it with the as keyword.
Let’s consider our include.py file. When we import it, and reference the code within, we have to use the file name as accessor.
To make it easier and faster to type we specify an alias for include.py that we can use when we access its items.
import module_name as alias_name
import include as inc # access code from imported file print(inc.message)
In the example above, we name our alias “inc” so that when we have to use it to access the variable inside the module we don’t have to type so much.
How to access built-in modules
Python has several built in modules, such as the math module, that contain useful functionality that we can import or import specific code from.
import math print("Pi = ", math.pi) print("Pi to ceiling = ", math.ceil(math.pi))
In the example above we access the variable “pi” and a function “ceil” from the math module.
Modules exist all over the internet with useful functionality that we can use. If we can think of it, it has most likely already been created into a module.
How to list all functionality in a module with the dir() function
Python has a nice built-in function that allows us to see the names of data containers / functions / classes in any imported module.
import math print(dir(math))
In the example above we list everything inside the math module.
We must import the file before we can list its contents.
How to reload a module at runtime
The interpreter only imports a module once during a session. It makes things more efficient. But, if our module code changed after it was imported, the changes would not be registered until the interpreter restarted.
Python allows us to use the reload() function to re-import a module at runtime.
The code above will automatically print when the module is imported.
import include import include import include
When we run the example above, we can see that the print statement from the module only printed once even though it was included 3 times.
When we reload, the interpreter will re-import the file but we need to import the reload() function itself from importlib .
# import reload() function from importlib import reload import include import include import include # reload the imported file reload(include)
In the example above, we first import the reload function from importlib. Then, we import the include file a few times to show that it only imports it once. Finally, we reload the include.py file. We can see that when the file reloaded it printed the “Code executed” statement again.
List of available modules
We can see all the modules in Python with the help() function. To display the list of modules we pass the word “modules” as a value.
It may take some time to render the list.
PythonTutorial _tkinter gettext runpy __future__ _tracemalloc glob sched _abc _warnings gzip secrets _ast _weakref hashlib select _asyncio _weakrefset heapq selectors _bisect _winapi hmac setuptools _blake2 abc html shelve _bootlocale aifc http shlex _bz2 antigravity idlelib shutil _codecs argparse imaplib signal _codecs_cn array imghdr site _codecs_hk ast imp smtpd _codecs_iso2022 asynchat importlib smtplib _codecs_jp asyncio include sndhdr _codecs_kr asyncore inspect socket _codecs_tw atexit io socketserver _collections audioop ipaddress sqlite3 _collections_abc base64 itertools sre_compile _compat_pickle bdb json sre_constants _compression binascii keyword sre_parse _contextvars binhex lib2to3 ssl _csv bisect linecache stat _ctypes builtins locale statistics _ctypes_test bz2 logging string _datetime cProfile lzma stringprep _decimal calendar macpath struct _dummy_thread cgi mailbox subprocess _elementtree cgitb mailcap sunau _functools chunk marshal symbol _hashlib cmath math symtable _heapq cmd mimetypes sys _imp code mmap sysconfig _io codecs modulefinder tabnanny _json codeop msilib tarfile _locale collections msvcrt telnetlib _lsprof colorsys multiprocessing tempfile _lzma compileall netrc test _markupbase concurrent nntplib textwrap _md5 configparser nt this _msi contextlib ntpath threading _multibytecodec contextvars nturl2path time _multiprocessing copy numbers timeit _opcode copyreg opcode tkinter _operator crypt operator token _osx_support csv optparse tokenize _overlapped ctypes os trace _pickle curses parser traceback _py_abc dataclasses pathlib tracemalloc _pydecimal datetime pdb tty _pyio dbm pickle turtle _queue decimal pickletools turtledemo _random difflib pip types _sha1 dis pipes typing _sha256 distutils pkg_resources unicodedata _sha3 doctest pkgutil unittest _sha512 dummy_threading platform urllib _signal easy_install plistlib uu _sitebuiltins email poplib uuid _socket encodings posixpath venv _sqlite3 ensurepip pprint warnings _sre enum profile wave _ssl errno pstats weakref _stat faulthandler pty webbrowser _string filecmp py_compile winreg _strptime fileinput pyclbr winsound _struct fnmatch pydoc wsgiref _symtable formatter pydoc_data xdrlib _testbuffer fractions pyexpat xml _testcapi ftplib queue xmlrpc _testconsole functools quopri xxsubtype _testimportmultiple gc random zipapp _testmultiphase genericpath re zipfile _thread getopt reprlib zipimport _threading_local getpass rlcompleter zlib Enter any module name to get more help. Or, type "modules spam" to search for modules whose name or summary contain the string "spam".
You may have noticed the PythonTutorial module at the very beginning of the list, as well as the include module further down.
These two modules are not built into Python, the PythonTutorial module is the name of the file we are using for the examples.
The include module is the one we used as an example of a module in this lesson.
Your own custom file names will appear in the list.
Summary: Points to remember
- A module is a separate file that can be included into the current document.
- We import whole modules with the import keyword.
- We import specific code inside a module with the from/import statement.
- Module members are accessed with dot notation.
- To see all of a module’s members, we use the dir() function.
- We manually re-import a module with the reload() function.