Importing Libraries

Python has a lot of features. So far, chapters have focused on core functionality. It is possible to "import" Python libraries that do more advanced work. These features are stored in groupings called "modules", "packages", or "libraries." There are some differences between these terms (for example, how they get installed on your system), but for now, they can be used interchangeably.

Learning Objectives

You should be able to:

  • Describe what importing does
  • Import libraries
  • Use imported library functions

Video Walkthrough

Use this video to follow along with the steps in this lab.

Importing

Python is broken down into modules. A Python file is a single module. Modules are organized in packages. Packages are folders of different modules. So there could be an entire package (i.e., folder) of Python modules (i.e., .py files) that could help you manipulate images, download web pages, decrypt data, and more.

Python comes with many packages that can be imported without having to install anything. In the next section, you will work with the datetime, os, and hashlib packages.

Datetime Library

Dates are hard. Really hard. Your average elementary school student knows how calendars and clocks work, but behind the basics lies a huge amount of complexity. Developers often get bitten by bugs due to leap years, leap seconds, time zones, and other date-related issues. Python's datetime library helps developers work with dates.

  • From the terminal, launch a Python interactive shell.

  • Run the following code to try to get the current date. (It will fail.)

datetime.date.today()
  • The code fails because the datetime package has not been loaded.
  • The entire datetime package can be imported with the following code.
import datetime
  • You can now access the datetime features.
datetime.date.today()
  • The code will now produce the correct date.
  • It is possible to specify a specific date.
datetime.date(2022, 6, 20)
  • Technically, you imported way more functionality than you needed to. If the only datetime feature we need is the date functionality, it can be imported specifically.
from datetime import date
date.today()

The above code goes into the datetime package and only loads the date module. Generally, only importing what you need and nothing else is preferred.

Os Library

Python's os library has information about operating system features.

  • Run the following code.
import os
  • This will print the name of the logged-in user'
  • Check to see if two folders exist.
os.path.exists("/")
os.path.exists("/home")
  • Check your current working directory.
os.getcwd()

Find other features here.

Hashlib Library

Python can be used to calculate hashes.

  • Run the following code.
import hashlib
hashlib.sha256(b"watermelon").hexdigest()
  • Notice the "b" in front of "watermelon". The "b" tells Python to treat the string "watermelon" as bytes (0s and 1s) using ASCII encoding.
  • To calculate the hash of a string variable, the bytes() function must be used.
word = "watermelon"
hashlib.sha256(bytes(word, 'ascii')).hexdigest()
  • The hashlib.sha256() function requires bytes (not a string), so the bytes() function converts the string to bytes according to the character encoding specified.
  • To see what else is in the hashlib library, run the following code:
dir(hashlib)
  • If you see something interesting, you can dig deeper into the official hashlib documentation.
  • For example, for password storage, scrypt would be better than sha256. Honestly, the Python documentation does not give a great explanation for using scrypt. But, the following code would work.
hashlib.scrypt(b"watermelon", salt=os.urandom(16), n=4, r=8, p=1)

Challenge: Hash Items in a List

The following code will hash a single password stored in the password variable:

import hashlib
password = "watermelon"
sha = hashlib.sha256(bytes(password, 'ascii'))
output = sha.hexdigest()
print(f"{password}:{output}")
  • Create a file called hashem.py.
  • Inside hashem.py, copy and then modify the above code:
    • Change the name of the password variables to passwords.
    • Set the value of the passwords variable to list of passwords (pick any random words).
    • Loop through each password in passwords.
    • In each loop, calculate the sha256 hash of the password.
    • Print the password and the hash, separated by a colon.

Reflection

  • What kinds of libraries would be most useful to help you solve problems?
  • Why is it a good idea to import the minimum number of libraries needed to solve a problem?

Key Terms

  • Python Imports: A mechanism in Python that allows you to include and use code from external modules and packages in your script. By using the import statement, you can access functions, classes, and variables defined in other files, promoting code reuse and modularity.