DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Updated on

Quick Intro to Python Modules

Subscribe to my email list now at http://jauyeung.net/subscribe/

Follow me on Twitter at https://twitter.com/AuMayeung

Many more articles at https://medium.com/@hohanga

Even more articles at http://thewebdev.info/

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at how to define and use modules to separate large programs into small pieces.

Importing Modules

Most programs are more than a few lines long. This means that they have to split into multiple small pieces for them to be manageable.

Python programs can be split into modules. Each module is a Python program. For example, the math module has math functions and the random module has random number-related functions.

To use Python modules in another module, we have to use the import keyword and the name of the module.

If we want to import more than one module, we can separate the module names by commas.

For example, we can import the random module and then print out a randomly generated number by calling the randrange function as follows:

import random  
print(random.randrange(0, 101, 2))

In the code above, we import the random module and called the randrange function with the start and end numbers of the number we want to generate as the first 2 arguments.

The end number is excluded from the range of numbers that can be generated.

The last argument has the number of steps to skip between the start and end numbers.

The code above will generate an even number in the range of 0 to 100 inclusive.

from import Statements

We can just import one member of a Python module with the from keyword.

For example, we can just import the randrange function from the random module as follows:

from random import randrange  
print(randrange(0, 101, 2))

In the code above, we just import the randrange function instead of the whole module.

But the rest of the logic is the same.

This is more efficient since we didn’t import everything.

Create Our Own Modules

Anything that is at the top level of a Python file can be imported from a Python module.

For example, we can create a module called foo.py as follows:

x = 1

Then in main.py , we can import and use it as follows:

import foo  
print(foo.x)

We should see 1 on the screen since we have x set to 1 and imported it.

The Module Search Path

Python modules are searched in the code directory, the path set as the value of the PYTHONPATH environment variable, and the default directory that’s set when Python is installed.

The dir() Function

The dir function is used to list the members of a Python module.

For example, we can print a list of members of the math module as follows:

import math  
print(dir(math))

Then we get the following on the screen:

['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

We can see the functions that we can call from the array above.

Packages

We can put Python files in directories to organize them into packages.

For example, we can put foo.py in the package folder, add __init__.py to it.

Then we can import and use package’s members as follows:

from package import foo  
print(foo.x)

Importing * From a Package

The asterisk character indicates that we import all the members from a package.

For example, if we write:

from sound.effects import *

we import all the members from the effects module in the sound package.

This is bad practice because we may have clashing names since we import more members than we’re supposed to.

Import as

We can use the as keyword to import a module with an alias name. This helps us avoid clashes of names from different modules where we have members that have the same name in different modules.

For example, we can write the following code:

import random as r  
print(r.randrange(0, 101, 2))

to import the random module with an alias r and reference that instead of random .

We can also import a member with as an alias as follows:

from random import randrange as rr  
print(rr(0, 101, 2))

We can call rr instead of randrange to call randrange .

Conclusion

We can define and import Python modules by creating a Python code file and then we can import the members of the Python file.

This lets us divide code into small pieces.

Also, we can organize Python modules into packages by putting module files in folders and add __init__.py to each directory.

Top comments (2)

Collapse
 
patryktech profile image
Patryk

[import *] is bad practice because the code is inefficient because we import everything. Also, we may have clashing names since we import more members than we’re supposed to.

I think it's bad practice because of the second part (name collisions), not really because "importing everything is inefficient."

AFAIK, there is no difference in doing import random and from random import * in terms of performance. It's just a different namespace.

As per the python documentation:

Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.

It doesn't mention performance, only readability.

Rest of the article looks good, though. Thanks for sharing.

Collapse
 
aumayeung profile image
John Au-Yeung

Thanks. I made the correction.