Skip to the content.

Persistence

-

Persistence

Files

-

dbm Module

The dbm module provides an interface for creating and updating database files.

-

Pickling

The pickle module can be used to serialize and de-serialize a Python object.

-

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"

-

Writting 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.

-

The End

Parrot