Python - Packages (2024)

Python - Packages (1)

'; var adpushup = adpushup || {}; adpushup.que = adpushup.que || []; adpushup.que.push(function() { adpushup.triggerAd(ad_id); });

In Python, the module is a Python script with a .py extension and contains objects such as classes, functions, etc. Packages in Python extend the concept of the modular approach further. The package is a folder containing one or more module files; additionally, a special file "__init__.py" file may be empty but may contain the package list.

Create a Python Package

Let us create a Python package with the name mypackage. Follow the steps given below −

  • Create an outer folder to hold the contents of mypackage. Let its name be packagedemo.
  • Inside it, create another folder mypackage. This will be the Python package we are going to construct. Two Python modules areafunctions.py and mathfunctions.py will be created inside mypackage.
  • Create an empty "__.init__.py" file inside mypackage folder.
  • Inside the outer folder, we shall later store a Python script example.py to test our package.

The file/folder structure should be as shown below −

Python - Packages (2)

Using your favorite code editor, save the following two Python modules in mypackage folder.

Example to Create a Python Package

# mathfunctions.pydef sum(x,y): val = x+y return val def average(x,y): val = (x+y)/2 return valdef power(x,y): val = x**y return val

Create another Python script −

# areafunctions.pydef rectangle(w,h): area = w*h return area def circle(r): import math area = math.pi*math.pow(r,2) return area

Let us now test the myexample package with the help of a Python script above this package folder. Refer to the folder structure above.

#example.pyfrom mypackage.areafunctions import rectangleprint ("Area :", rectangle(10,20))from mypackage.mathsfunctions import averageprint ("average:", average(10,20))

This program imports functions from mypackage. If the above script is executed, you should get following output

Area : 200average: 15.0

Define Package List

You can put selected functions or any other resources from the package in the "__init__.py" file. Let us put the following code in it.

from .areafunctions import circlefrom .mathsfunctions import sum, power

To import the available functions from this package, save the following script as testpackage.py, above the package folder as before.

Example to Define a Package List

#testpackage.pyfrom mypackage import power, circleprint ("Area of circle:", circle(5))print ("10 raised to 2:", power(10,2))

It will produce the following output

Area of circle: 78.5398163397448310 raised to 2: 100

Package Installation

Right now, we are able to access the package resources from a script just above the package folder. To be able to use the package anywhere in the file system, you need to install it using the PIP utility.

First of all, save the following script in the parent folder, at the level of package folder.

#setup.pyfrom setuptools import setupsetup(name='mypackage',version='0.1',description='Package setup script',url='#',author='anonymous',author_email='[email protected]',license='MIT',packages=['mypackage'],zip_safe=False)

Run the PIP utility from command prompt, while remaining in the parent folder.

C:\Users\user\packagedemo>pip3 install .Processing c:\users\user\packagedemo Preparing metadata (setup.py) ... doneInstalling collected packages: mypackage Running setup.py install for mypackage ... doneSuccessfully installed mypackage-0.1

You should now be able to import the contents of the package in any environment.

C:\Users>pythonPython 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import mypackage>>> mypackage.circle(5)78.53981633974483

Advertisem*nts

';adpushup.triggerAd(ad_id); });

Python - Packages (2024)
Top Articles
BMW Motors Sources of Competitive Advantage
PESTLE Analysis of BMW: Shaping the automotive industry
El Paso Pet Craigslist
East Cocalico Police Department
Ofw Pinoy Channel Su
What Happened To Dr Ray On Dr Pol
Recent Obituaries Patriot Ledger
Sam's Club Gas Price Hilliard
Paula Deen Italian Cream Cake
Progressbook Brunswick
FIX: Spacebar, Enter, or Backspace Not Working
Walgreens On Nacogdoches And O'connor
Healing Guide Dragonflight 10.2.7 Wow Warring Dueling Guide
Gon Deer Forum
Viprow Golf
Xomissmandi
The best TV and film to watch this week - A Very Royal Scandal to Tulsa King
Scout Shop Massapequa
Graphic Look Inside Jeffrey Dahmer
Heart Ring Worth Aj
Company History - Horizon NJ Health
HP PARTSURFER - spare part search portal
Lininii
Lawrence Ks Police Scanner
Tokioof
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
Homewatch Caregivers Salary
Grand Teton Pellet Stove Control Board
Navigating change - the workplace of tomorrow - key takeaways
Kelly Ripa Necklace 2022
Joey Gentile Lpsg
18 terrible things that happened on Friday the 13th
Skyward Marshfield
Engr 2300 Osu
How to Quickly Detect GI Stasis in Rabbits (and what to do about it) | The Bunny Lady
'Guys, you're just gonna have to deal with it': Ja Rule on women dominating modern rap, the lyrics he's 'ashamed' of, Ashanti, and his long-awaited comeback
814-747-6702
Rush Copley Swim Lessons
Tricare Dermatologists Near Me
Brown launches digital hub to expand community, career exploration for students, alumni
Timothy Warren Cobb Obituary
Perc H965I With Rear Load Bracket
Hawkview Retreat Pa Cost
Iman Fashion Clearance
Ts In Baton Rouge
Zeeks Pizza Calories
A rough Sunday for some of the NFL's best teams in 2023 led to the three biggest upsets: Analysis
Spn 3464 Engine Throttle Actuator 1 Control Command
Sleep Outfitters Springhurst
Razor Edge Gotti Pitbull Price
Nfsd Web Portal
Bones And All Showtimes Near Emagine Canton
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 5996

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.