in , ,

Python Packages: How to create and import them?

Python Packages: How to create and import them?

Python Package

In this article, you’ll learn to divide your codebase into clean, efficient modules using Python packages. also, you’ll learn import and use your own or third-party packages in your Python program.

What are the packages?

We don’t usually store the entirety of our files on our computer in a similar area. We use an efficient chain of command of registries for simpler access.

Python has packages for directories and modules for files.

As our application program grows larger in size with a lot of modules, we place comparative modules in a single bundle and various modules in various bundles. This makes an undertaking (program) simple to oversee and reasonably clear.

Similarly, as a directory can contain subdirectories and records, a Python bundle can have sub-bundles and modules.

A directory must contain a document named __init__.py in order for Python to consider it as a package. This file can be left vacant yet we for the most part place the statement code for that bundle in this document.

Here is an example. Suppose we are developing a game. One possible organization of packages and modules could be as shown in the figure below.

PackageModuleStructure

Importing module from a package

We can import modules from packages using the dot (.) operator.

For example, if we want to import the start module in the above example, it can be done as follows:

import Game.Level.start

Now, if this module contains a function named select_difficulty(), we must use the full name to reference it.

Game.Level.start.select_difficulty(2)

If this construct seems lengthy, we can import the module without the package prefix as follows:

from Game.Level import start

We can now call the function simply as follows:

start.select_difficulty(2)

Another method of bringing in simply the necessary capacity (or class or variable) from a module inside a bundle would be as per the following:

from Game.Level.start import select_difficulty

Now we can directly call this function.

select_difficulty(2)

Although easier, this method is not recommended. Using the full namespace avoids confusion and prevents two same identifier names from colliding.

While importing packages, Python looks in the list of directories defined in sys. path, similar to the module search path.


Please feel free to give your comment if you face any difficulty here.

For More Latest Articles Click on Below Link.

salman khan

Written by worldofitech

Leave a Reply

Python Modules

Python Modules

Python Numbers, Type Conversion and Mathematics

Python Numbers, Type Conversion and Mathematics