Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Writing a Module

In this lesson, you’ll learn the fundamentals of writing a module. There are three ways to define a module in Python:

  1. A module can be written in Python itself.
  2. A module can be written in C and loaded dynamically at run-time, like the re (regular expression) module.
  3. A built-in module is intrinsically contained in the interpreter, like the itertools module.

A module’s contents are accessed the same way in all three cases: with the import statement.

Here, the focus will mostly be on modules that are written in Python. The cool thing about modules written in Python is that they are pretty straightforward to build. All you need to do is create a file that contains legitimate Python code and then give the file a name with a .py extension. That’s it! You don’t need any special syntax.

For example, suppose you have created a file called mod.py containing the following:

s = "Computers are useless. They can only give you answers."
a = [100, 200, 300]

def printy(arg):
    print(f'arg = {arg}')

class Classy:
    pass

Several objects are defined in mod.py:

  • s: a string
  • a: a list
  • printy(): a function
  • Classy: a class

Assuming mod.py is in an appropriate location, which you’ll learn more about shortly, these objects can be accessed by importing the module as follows:

>>>
>>> import mod
>>> mod.a
[100, 200, 300]
>>> mod.s
'Computers are useless. They can only give you answers.'
>>> mod.printy('What is up!')
arg = What is Up!
>>> x = mod.Classy()
>>> x
<mod.Classy object at 0x03C181F0>

This courses uses the VS Code editor in the coding examples. If you’d like to learn more about this editor setup, please consult our VS Code Setup Guide.

Here are a few links for details on using bpython, the REPL (Read–Eval–Print Loop) tool used in most of these videos:

Become a Member to join the conversation.