Modules

Intermediate Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

What are modules?

  • Modules are Python scripts
    • Files ending with .py
    • Contain functions and attributes
    • Can contain other modules

$$

$$

$$

  • Help us avoid rewriting code that already exists!

Man looking at reflection, seeing further reflections

Intermediate Python for Developers

Python modules

  • os:
    • Used for interacting with our operating system
    • Check the current directory
    • List available files
    • Access environment variables
  • string:
    • Simplifies text processing tasks

Python modules

Intermediate Python for Developers

Importing a module

# General syntax
import <module_name>
# Import the os module
import os
# Check the type
print(type(os))
<class 'module'>
Intermediate Python for Developers

Finding a module's functions

# Call help()
# Warning - will return a very large output!
print(help(os))
Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

MODULE REFERENCE
    https://docs.python.org/3.12/library/os.html
    ...
Intermediate Python for Developers

Getting the current working directory

# Using an os function
print(os.getcwd())
/home/courses/intermediate_python_for_developers

$$

  • Useful if we need to reference the directory later
# Assign to a variable
work_dir = os.getcwd()
Intermediate Python for Developers

Changing directory

# Changing directory
os.chdir("/home/courses")
# Check the current directory
print(os.getcwd())
/home/courses
# Confirm work_dir has not changed
print(work_dir)
/home/courses/intermediate_python_for_developers
Intermediate Python for Developers

Module attributes

  • Attributes return values
  • Functions perform tasks
  • Don't use parentheses with attributes
# Get the local environment
print(os.environ)
environ{'PATH': '/usr/local/bin',
        'TERM': 'xterm',
        'HOSTNAME': '097a0fe4-d6ce-4325-a6e2-1d0ce2800c2b',
        'TZ': 'Europe/Brussels',
        'LANG': 'en_US.UTF-8',
         ...
Intermediate Python for Developers

String module

import string


print(string.ascii_lowercase)
abcdefghijklmnopqrstuvwxyz

$$

  • Check if a string contains letters, numbers, or specific characters

$$

  • Handy for validating user input 💡
print(string.digits)
0123456789

$$

print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Intermediate Python for Developers

Let's practice!

Intermediate Python for Developers

Preparing Video For Download...