Skip to the content.

Modules & Packages

-

Modules

-

What Is It?

A module is a file consisting of Python code. A module can define functions, classes and variables.

-

Importing modules

Python code in one module gains access to the code in another module by the process of importing it.

The import statement is the most common way of invoking the import machinery.

The imported module must be accessed using its full qualified name rather than directly.

import math

math.pi
# 3.141592653589793

math.ceil(2.2)
# 3

math.factorial(5)
# 120

-

Importing modules

When using the from clause, the reference is stored in the local namespace.

from math import sqrt

sqrt(25)
# 5.0

-

Writing modules

my_module.py

def say_hello():
    print("Hello")

say_hello()

app.py

import my_module as mm
# output "Hello"

-

Writing modules

my_module.py

def say_hello():
    print("Hello")

if __name__ == '__main__':
    say_hello()

app.py

import my_module as mm
# no output

say_hello()
# output "Hello"

-

Packages

-

What Is It?

A package is a module that can contain other modules.
A package is a directory containing a file named __init__.py.
The __init__.py file is executed when the package is imported.
A package can contain subpackages.

-

Packages

Packages are often collections of modules

Often packages contain commonly used functionality

See requests at PyPI

You’ll use pip install to add them to your venv

-

Requests

Requests is a simple, yet elegant, HTTP library.

>>> import requests
>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
'{"authenticated": true, ...'
>>> r.json()
{'authenticated': True, ...}

-

Requests

Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your PUT & POST data — but nowadays, just use the json method!

Requests is one of the most downloaded Python packages today, pulling in around 30M downloads / week— according to GitHub, Requests is currently depended upon by 1,000,000+ repositories. You may certainly put your trust in this code.

-

The End

Parrot