Welcome to

Mimpi Development

Developing for tomorrow, one dream at a time

Packages and Modules

Posted on 24 Feb 2019 in Blog, Learning to Program | 0 comments

Now that you’ve done the most basic program, everybody learns first, “Hello World”, lets look at including libraries. This is where you start to have fun.

The import keyword

We have already covered the path of execution of code, including libraries that are included in your program. To include a module into your project code use the following:

import modu

This will include the modu module for use in your program, allowing you to use any classes or functions in the module. Your other option is to include the function or the class from the module.

from modu import sqrt

This would allow you to call the function directly as if it was part of your own code

x = sqrt(4)

Best practice though, and the reason I mentioned it first, is to include the entire module and use it in your code

x = modu.sqrt(4)

Packages

The wonderful people who brought us python, gave us a packaging system, which is an extension of the module mechanism on a given directory. Any directory where a __init__.py file is found is considered a python package. The modules within a package are imported like plain modules, but the __init__.py file is special, in that you use it to gather all package-wide definitions.

To import a module from a package you do the following:

import pack.modu

This imports the modu.py module found in the “pack” directory. Upon hitting the above import statement, it will initially look for the aforementioned __init__.py file and execute it. Then it will look for the module “modu.py” and execute it. After this, any variable function or class defined is available in the pack.modu namespace.

One of the biggest tips for using __init__.py is this: Type to avoid too much code in it. As your project complexity grows, and you wind up using packages within packages, When you import the children, or grand-children packages, be warned: Python will execute all __init__.py files while traversing the tree. Normal practice is to leave the __init__.py files blank when modules and child packages do not require the sharing of code.

When working with grand-child packages, you can alias the module so you can make you code a little cleaner:

import parent.child.grandchild.module as mod
x = mod.sqrt(4)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.