You are on page 1of 1

Modules

An object that serves as an organizational unit of Python code. Modules have a


namespace containing arbitrary Python objects. Modules are loaded into
Python by the process of importing.

In practice, a module usually corresponds to one .py file containing Python


code.
Ej:
import math → import the code in the math module
math.pi → access the pi variable within the math module

Namespaces
A namespace is a collection of currently defined symbolic names along with
information about the object that each name references. You can think of a
namespace as a dictionary in which the keys are the object names and the
values are the objects themselves. Each key-value pair maps a name to its
corresponding object.
In addition to being a module, math acts as a namespace that keeps all the
attributes of the module together.

You can list the contents of a namespace with dir() Ej: dir (math)
Using dir() without any argument shows what’s in the global
namespace.

from math import pi


math.pi
NameError: name 'math' is not defined

Note that this places pi in the global namespace and not within a math
namespace.

You can also rename modules and attributes as they’re imported:


import math as m

m.pi

from math import pi as PI

You might also like