Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Files, Modules and Packag...
  5. Packages

Packages

Packages are a way of structuring many packages and modules which helps in a well – organized hierarchy of data set, making the directories and modules easy to access.

Creating a package

To make a directory as package, create a file name __init__.py inside it. The __init__.py file can be left blank or can be coded with the initialization code for the package.

In general steps to create a package are,

  • Create a directory (folder) and give it a package name
  • Then put the classes and required functions in it
  • Create an __init__.py file inside the directory

Example

Using keyword import

To import a module name mod1 then, use the syntax as

import MyPackage1.p1.mod1

If the module mod1 contains the function add( ), to access the function use the syntax as

MyPackage1.p1.mod1.add()

Using the key word from… import

Importing the module without the package prefix as

from MyPackage1.p1 import mod1

Now the function, add( ) in mod1 can be accessed as

mod1.add( )

Importing just the required function (or class or variable) from module present in a package

Syntax

from MyPackage1.p1.mod1 import add

Now the function, add( ) in mod1 can be accessed as

add( )

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments