Trusted answers to developer questions

What are Python packages?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

A python package is a collection of modules. Modules that are related to each other are mainly put in the same package. When a module from an external package is required in a program, that package can be imported and its modules can be put to use.

Any Python file, whose name is the module’s name with the .py extension, is a module.

A package is a directory of Python modules that contains an additional __init__.py file, which distinguishes a package from a directory that is supposed to contain multiple Python scripts. Packages can be nested to multiple depths if each corresponding directory contains its own __init__.py file.

svg viewer

When you import a module or a package, the object created by Python is always of type module.

When you import a package, only the methods and the classes in the __init__.py file of that package are directly visible.

Code

For example, let’s take the datetime module, which has a submodule called date. When datetime is imported, it’ll result in an error, as shown below:

Press + to interact
import datetime
date.today()

The correct way to use the date module is shown below:

Press + to interact
from datetime import date
print date.today()

RELATED TAGS

python
packages
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?