3 min read•june 24, 2024
Python's module system allows you to and use classes other files, promoting code organization and reusability. By importing specific classes or using aliases, you can streamline your code and make it more readable.
Modules help group related classes together, making your codebase more manageable. This approach supports concepts like and , while also enabling the creation of larger, more complex .
from
keyword followed by module name and import
keyword to import specific classes from a module
from module_name import ClassName1, ClassName2
from [math](https://www.fiveableKeyTerm:Math) import [sqrt](https://www.fiveableKeyTerm:sqrt), [pi](https://www.fiveableKeyTerm:pi)
sqrt
function and pi
constant from math
modulesqrt(x)
and pi
directly in code without prefixing with math.
from [datetime](https://www.fiveableKeyTerm:datetime) import [date](https://www.fiveableKeyTerm:date), [time](https://www.fiveableKeyTerm:Time)
date
and time
classes from datetime
moduledate
and time
classes directly, e.g., today = date.today()
[as](https://www.fiveableKeyTerm:as)
keyword to give an alias to an imported module or class
import module_name as alias
or from module_name import ClassName as alias
import [numpy](https://www.fiveableKeyTerm:NumPy) as np
numpy
module and assigns it alias np
np
instead of numpy
to refer to the module, e.g., np.array([1, 2, 3])
from [matplotlib](https://www.fiveableKeyTerm:Matplotlib) import [pyplot](https://www.fiveableKeyTerm:pyplot) as plt
pyplot
module from matplotlib
and assigns it alias plt
plt
instead of pyplot
to refer to the module, e.g., plt.plot(x, y)
shapes.py
containing related classes like [Circle](https://www.fiveableKeyTerm:Circle)
, [Rectangle](https://www.fiveableKeyTerm:Rectangle)
, and [Triangle](https://www.fiveableKeyTerm:Triangle)
shapes
module:
from shapes import Circle, Rectangle, Triangle
Circle
, Rectangle
, and Triangle
classes in main programutils.py
containing utility classes like [FileHandler](https://www.fiveableKeyTerm:FileHandler)
, [DatabaseConnector](https://www.fiveableKeyTerm:DatabaseConnector)
, and [Logger](https://www.fiveableKeyTerm:Logger)
import package.subpackage.module