0% found this document useful (0 votes)
22 views

Python

Modules are objects that organize Python code into namespaces. A module corresponds to a .py file and is loaded through importing. Namespaces are collections of symbolic names mapped to objects, and modules act as namespaces that group an object's attributes. Importing modules places their contents in a namespace, while importing specific attributes places them in the global namespace without the module namespace.

Uploaded by

pepe
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python

Modules are objects that organize Python code into namespaces. A module corresponds to a .py file and is loaded through importing. Namespaces are collections of symbolic names mapped to objects, and modules act as namespaces that group an object's attributes. Importing modules places their contents in a namespace, while importing specific attributes places them in the global namespace without the module namespace.

Uploaded by

pepe
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 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