How to Create a package and import its module using import command|how to create a package and import it in python|how to create a package in python

 Introduction

In this blog we are going to learn- How to Create a package and import its module using import command.
This program is also in the list of CBSE class 12 computer science practical list.

So major steps for performing this task is:-
  • Creating a Folder
  • Creating an empty __init__.py file in that folder.
  • creating a .py file and defining the functions.
  • saving the folder in the correct path of pythons site packages.
Major steps to use the package is:
  • Using import command.

You can name the folder anything you want.
You can know the purpose of creating __init__.py file in the end of this blog.

  • creating a .py file and defining the functions.
  • Sample code of a .py is as follows:-

Vs=4/3*3.14
vc=1/3*3.14
vcy=3.14
def volumeofsphere(r):
    return(Vs*r*r*r)
def Volumerofcone(r,h):
    "ReturnsVolumeofCone"
    return(vc*r*r*h)
def Volumeofcylinder(r,h):
    "ReturnsVolumeofCylinder"
    return(vcy*r*r*h)

FOR instance let's name this file as "volume.py" and save it in the path of your python site-packages folder.
To get the path of site packages folder...Run the following code:-

import sys
print(sys.path)

Copy-paste .py file in folder ;that is generated by the above code.

Now to use the defined functions in the module use this format.
  • import "module name or .py file name(volume)"
  • then use volume.Volumeofcylinder(radius,height)

About __init__.py file:-
The Python interpreter recognizes a folder as the package if it contains __init__.py file.

"Hope it helped"
Have anything in mind? Let me 
know in the comment section👇

Next Post Previous Post
1 Comments
  • Unknown
    Unknown October 13, 2021 at 7:22 PM

    Great website 👍🏻!

Add Comment
comment url