How to create your own package in python
In this tutorial, you are going to learn how you can create your own package in python.
Package in python:
In the packages, we create a special file named __init__.py which is simply a file that is used to consider the direction on the disk as the package of the python. It can initialize a package.
Steps to create a package:
- Create the new folder which will have the modules and the sub packages.
- Make an empty file (i.e., no text) and save it in the folder having the name __init__.py
- Import this package in your main program and use the function of the module in your main program.
An example of how to create your own package in Python
Step 1: Make a new folder with the name pack ( you can change the name of the folder according to yourself).
Step 2: Make an empty file having name __init__.py ( you can’t change the name of the file) and save it in the pack folder. This file specifies that the folder in which it is saved is a package of python.
Step 3: Create the first module which will have the function definition. Save this file as basic.py (you can change the name) in the pack folder.
# function definition 1 def add(a,b): c=a+b print("Addtion:",c) return # function definition 2 def sub(a,b): c=a-b print("Subtraction:",c) return # function definition 3 def mul(a,b): c=a*b print("Multiplication:",c) return # function definition 4 def div(a,b): c=a/b print("Division:",c) return
Step 4: Create the second module and save it as an area.py (you can change the name of the file) in the pack folder.
Note: You can create as many modules as you want in the pack folder.
# function definition 1 def circle(r): print("Area of circle:",3.14*r*r) return # function definition 2 def square(l): print("Area of square:",l*l) return # function definition 3 def rectangle(l,b): print("Area of rectangle:",l*b) return # function definition 4 def triangle(b,h): print("Area of triangle:",0.5*b*h) return
Step 5: Import this package in the main program.
# importing 1st module from pack.basic import* # importing 2nd module from pack.area import* # function call from 1st module add(10,20) sub(30,10) mul(10,4) # function call from 2nd module circle(5) square(4)
Output:-
Addtion: 30 Subtraction: 20 Multiplication: 40 Area of circle: 78.5 Area of square: 16
Note: The main program will be saved outside the pack folder, i.e., it should not be saved in the pack folder. If you saved the main program in the pack folder, then it will create an error.
Go and check other tutorials on python:
I completed and executes the above code you told. But my main program throws error that
NameError: name ‘add’ is not defined.
Later I comment the functions one by one and runs it. It says NameError for all functions.
Please clear my problem.