Python: How to Write a Module

By Xah Lee. Date: . Last updated: .

You can define functions, save it in a file, then later on, load the file and use these functions. For example, save the following line in a file and name it

# -*- coding: utf-8 -*-
# python

def f1(n):
    return n+1

To load the file, use import import xy, then to call the function, use xy.f1. Example:

# -*- coding: utf-8 -*-
# python

import xy # import the module

print xy.f1(5)  # calling a function

See also:

Python Module/Package/Namespace Details

If you have multiple files, they make up a package. You put all files inside directory, possibly with nested sub directories. Like this:


For example, in the above, you can load a module by:

import fangame.soundx.rabbit_punch
import fangame.thinky.subby.a
# ...

Dir with means that directory is part of the package. Python will look at the dir structure and file names as module's name when import is called.

For example, if dir soundx does not have a file, then import fangame.soundx.rabbit_punch won't work, because Python won't consider dir soundx as part of the package.

Similarly, fangame must have a And, if you want import fangame to automatically load soundx/rabbit_punch, then, in fangame/ you must have import soundx.rabbit_punch.

The file will be executed when that particular module in that directory is loaded. If you don't need any such init file, just create a empty file.

Here's a summary:

Note: it is suggested that module names be short and lower case only.

Note: the Python language does not have direct technical concept of “module” nor “package”. For example, there's not keyword “module” nor “package”. These words are only used to describe the concept of libraries. Technically, Python language only has a sense of namespace, and is exhibited by {import,, __name__, __all__, …}.

Syntax 「from x.y import z」

Alternative syntax for loading module is from x.y import z.

Typically, this is used to import the name z, of single function z of module file at x/ But the actual semantics is a bit complex.

from x.y import z will do ONE of two things:

If the module x/ doesn't have the name z, and there's no module at x/y/, then a ImportError is raised.

Syntax 「from x.y import *」

Another syntax for loading module is from x.y import *.

from x.y import * will do this:

If the file at x/y/ defines a variable named __all__ (which should contain a list of strings, each string is a submodule name), then, all those sub-modules are imported. The names imported are the strings of __all__.

For example, if __all__ = ["a","b"], then the module at x/y/ is imported as name a and the module at x/y/ is imported as name b.

If __all__ is not defined, then from x.y import * just imports the name x.y (for module x/ and all names from module x/

2014-04-09 Thanks to Kaito Kumashiro for correction. Thanks to Demian Brecht for suggestion.

Python: Paths Topic

  1. File Path Manipulation
  2. Print Version String from Script
  3. Executable Path, Script Path
  4. List Modules, Search Path, Loaded Modules
  5. How to Write a Module

If you have a question, put $5 at patreon and message me.

Python by Example

  1. Python Basics
  2. Print Version String
  3. Builtin Help
  4. Quote String
  5. String Operations
  6. String Methods
  7. Format String
  8. True, False
  9. if then else
  10. for, while, Loops
  11. List Basics
  12. Loop Thru List
  13. Map Function to List
  14. List Comprehension
  15. List Methods
  16. Dictionary
  17. Loop Thru Dict
  18. Dict Methods
  19. Function
  20. Class
  21. List Modules
  22. Write a Module
  23. Unicode 🐍


  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. Manipulate Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency


  1. Send Email
  2. GET Web Page
  3. Web Crawler


  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Complex Numbers
  7. Sort
  8. Copy Nested List
  9. Tuple vs List
  10. Sets, Union, Intersection
  11. Closure in Python 2
  12. Decorator
  13. Append String in Loop
  14. Timing f timeit
  15. Keyword Arg Default Value Unstable
  16. Check Page Load Size
  17. Thumbnail Generation

Python 3

  1. Python 3 Basics
  2. Print Version String
  3. Quoting String
  4. String Operations
  5. Format String
  6. Operators
  7. Object, ID, Type
  8. Traverse Directory
  9. Sort List, Matrix, Object
  10. Python 3: Map with Side Effect Doesn't Work If Result is Not Used
  11. Python 3 Closure
  12. Python 2 and 3 Difference