Import Python Packages and Modules (2024)

Import Python Packages and Modules (1)

Import a Python package

As you have already seen, to make use of a Python module in the Python Standard Library you can use the syntax that you are already familiar with:

import <module>

For example, if you want to use the os module from the Python Standard Library to print the current working directory of a process, you could create a file called script.py with the following contents:

import osprint(os.getcwd())

You could then run script.py from the terminal using python script.py :

~→ python script.py/Users/george~→

In the script we import the entire os module and make use of a piece of its functionality by calling os.getcwd().

As an alternative to this, we can instead choose to import selected functionality from the os package as follows:

from os import getcwdprint(getcwd())

We import third-party Python packages into Python files in the same way as we import modules from the Python Standard Library into Python files. For example, we could make use of the numpy package to round numbers up and down.

First, let’s install numpy by running pip install numpy from the command line terminal:

→ pip install numpyCollecting numpyUsing cached https://files.pythonhosted.org/packages/5c/f5/0e5e57fa7683cf0e5036320f4676cd7e3dbd9ab8c17ada541c2bb5ebed5e/numpy-1.19.0-cp37-cp37m-macosx_10_9_x86_64.whlInstalling collected packages: numpySuccessfully installed numpy-1.19.0~→

Now, we can import numpy in a Python script and use it to round some numbers up and down. Create a Python script called number_rounding.py and put the following code into your script:

import numpyprint(numpy.ceil(1.2))print(numpy.ceil(1.933))print(numpy.floor(1.2))

As you can see, we import the third-party numpy Python package in the same way as we would import modules in the Python Standard Library such as json , os , datetime and re. Running number_rounding.py should generate the following output:

→ python number_rounding.py2.02.01.0~→

Import everything from a Python package

An alternative to using the import <package> syntax is to instead import everything from a package using from <package> import * . This can be useful when you are using the Python shell, because it means you can type less.

For example, let’s start by opening the Python shell by typing python in the command line terminal:

→ pythonPython 3.7.1 (default, Dec142018, 13:28:58)[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwinType "help", "copyright", "credits" or "license" for more information.>>>

Now, let’s import everything from the numpy package using from numpy import * :

→ pythonPython 3.7.1 (default,Dec142018,13:28:58)[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwinType "help", "copyright", "credits" or "license" for more information.>>> from numpy import *>>>

Now, we can use the ceil() and floor() methods without having to prefix them with numpy :

→ pythonPython 3.7.1 (default, Dec142018, 13:28:58)[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwinType "help", "copyright", "credits" or "license" for more information.>>> from numpy import *>>> ceil(1.2)2.0>>> floor(1.2)1.0

While using from <package> import * in the Python shell is fine, it generally isn’t considered good practice in application source code. If you use from <package_a> import * and from <package_b> import * and there is a name clash between functionality in package_a and functionality in package_b, then this mightresult inunintended consequences.

Aliasing packages

When importing packages you also have the option to import them with an alias using the command import <package> as <alias>. Strangely, this is industry standard for some packages, but would be considered unconventional for other packages.

For example, it is in fact industry standard to importnumpy using import numpy as np . If we apply this style of import to number_rounding.py , it would become:

import numpy as npprint(np.ceil(1.2))print(np.ceil(1.933))print(np.floor(1.2))

It’s functionality remains unchanged, so when we run it using Python the output is exactly the same:

→ python number_rounding.py2.02.01.0~→

Using the np alias in this case means that for large applications with lots of source code, the code becomes slightly easier to read and understand, and thus more maintainable/extendable.

You can choose to use any alias you wish, but it is generally best to use something which could be considered shorthand for the package name. Usingimport numpy as apples wouldn’t make much sense, for example!

For a bit more information around importing Python packages, check out this screencast:

Let’s Recap!

Now that you have completed this chapter you should be confident with the following tasks:

  • You can import Python packages into Python files in the same way as importing modules from the Python Standard Library.

  • It is good practice to become familiar with, and accustomed to, a variety of methods for importing modules and packages and then choosing the most appropriate import method for your particular use case.

Now that you are more confident with importing packages and modules into Python files, let’s take a look at why versioning of packages is so important in software development.

Import Python Packages and Modules (2024)
Top Articles
Does Homeowners Insurance Cover Foundation Issues? – Policygenius
Credit Cards for No Credit History | Discover
Use Copilot in Microsoft Teams meetings
Foxy Roxxie Coomer
Top 11 Best Bloxburg House Ideas in Roblox - NeuralGamer
Chris Provost Daughter Addie
Housing near Juneau, WI - craigslist
Gamevault Agent
1970 Chevelle Ss For Sale Craigslist
Kansas Craigslist Free Stuff
Hk Jockey Club Result
Georgia Vehicle Registration Fees Calculator
Obituary (Binghamton Press & Sun-Bulletin): Tully Area Historical Society
Nm Remote Access
Cvs Devoted Catalog
Mndot Road Closures
Weather In Moon Township 10 Days
Zoebaby222
U/Apprenhensive_You8924
Red Tomatoes Farmers Market Menu
A rough Sunday for some of the NFL's best teams in 2023 led to the three biggest upsets: Analysis - NFL
Non Sequitur
2015 Honda Fit EX-L for sale - Seattle, WA - craigslist
Velocity. The Revolutionary Way to Measure in Scrum
Aspen Mobile Login Help
Craigslist Maui Garage Sale
Yard Goats Score
Empire Visionworks The Crossings Clifton Park Photos
Rs3 Ushabti
Meridian Owners Forum
Mikayla Campinos: Unveiling The Truth Behind The Leaked Content
10 Best Places to Go and Things to Know for a Trip to the Hickory M...
Ardie From Something Was Wrong Podcast
Leben in Japan &#8211; das muss man wissen - Lernen Sie Sprachen online bei italki
Maths Open Ref
5 Star Rated Nail Salons Near Me
Package Store Open Near Me Open Now
Chadrad Swap Shop
Flaky Fish Meat Rdr2
Mega Millions Lottery - Winning Numbers & Results
Sinfuldeeds Vietnamese Rmt
Junior / medior handhaver openbare ruimte (BOA) - Gemeente Leiden
The 50 Best Albums of 2023
Join MileSplit to get access to the latest news, films, and events!
Wunderground Orlando
Emulating Web Browser in a Dedicated Intermediary Box
Unblocked Games Gun Games
boston furniture "patio" - craigslist
Expendables 4 Showtimes Near Malco Tupelo Commons Cinema Grill
Union Supply Direct Wisconsin
Free Carnival-themed Google Slides & PowerPoint templates
sin city jili
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 5610

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.