What is a python package? Flashcards

(5 cards)

1
Q

general summary

A

In Python, a package is a way to organize related modules.

Packages are directories with a special __init__.py file that indicates they’re Python packages.

mypackage/
    \_\_init\_\_.py
    module1.py
    module2.py
    subpackage/
        \_\_init\_\_.py
        submodule1.py
        submodule2.py
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Features of a package

A

Modularize Code: Group related functionality.

Encapsulate State: By using underscores (_) in the module names, you can indicate that certain modules or attributes are for internal use.

Control Scope: The __init__.py file can specify the modules to be imported when the package is imported. This can, in a way, control scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Package Directories

A

Packages are directories that contain an __init__.py file. When a directory has an __init__.py file, Python understands it as a package. This mechanism allows for hierarchical structuring of project

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s Inside __init__.py?

A

The __init__.py file is optional, but it’s a good practice to have one. It lets you do many things when the package is first imported, such as setting up package-level resources, initializing variables or data, or defining methods that are available as part of the package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Best Practices

A

Choose Descriptive Names: Make sure those names aren’t already taken by existing packages on, say, PyPI.

Follow PEP 8 Naming Conventions: Use lowercase names, and heed the guideline to avoid leading underscores.

Use Relative Imports: This is especially important in larger packages with many code files. It ensures your import system doesn’t break if you change the absolute module path.

Use:

from . import module1
from .subpackage import submodule1

Avoid:

from mypackage import module1  # using absolute import
How well did you know this?
1
Not at all
2
3
4
5
Perfectly