Modules
Python code is organized into
modules
.
A module must be loaded into memory using the
import statement. Some modules are built into
Python and always available; others are stored in external files.
Modules can also be written either in C (in which case they are
compiled as a special kind of DLL) or in Python (in which case they
are saved in text files ending in
.py
). As far
as the user is concerned, they are all used the same way:
>>> import math >>> math.sin(math.pi/2) 1.0 >>>
We used both a function and a constant from the
math module. Note that the module’s name
must be prefixed. This prevents namespace
collisions: imagine how many different programs might wish to define
a function called read( ) or save(
). It’s also possible to import a function explicitly
into the present namespace:
>>> from string import split, join
>>> split('We are the knights who say Ni')
['We', 'are', 'the', 'knights', 'who', 'say', 'Ni']
>>>This procedure can be used for brevity but increases the risk of a collision, and, more important, of losing track of what your code means a few months later. It should be used sparingly.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access