A10 Modules

Custom Module

# Using a custom module defined in the same directory
# ------------------------------------------------------------------------------
# A *module* is simply a Python file that defines variables, functions, or
# classes. This example imports ``mymodule`` and calls its functions. Modules
# help organize related code and can be reused across projects.

import mymodule

print(mymodule.greet('World'))
print('Area of circle:', mymodule.area_circle(3))
print('Module name:', mymodule.__name__)

Builtin Modules

# Using built-in Python modules
# ------------------------------------------------------------------------------
# Python ships with a rich *standard library* of modules that you can use
# without installing anything extra. This example demonstrates ``math`` and
# ``random``.

import math
import random

print('Square root of 16 is', math.sqrt(16))
print('Value of pi is', math.pi)
print('Random number between 1 and 6:', random.randint(1, 6))

Package Import

# Importing from a package
# ------------------------------------------------------------------------------
# A *package* is a directory containing an ``__init__.py`` file and one or more
# modules. Packages allow related modules to be grouped together. This example
# imports the ``hello`` function from ``my_package`` defined in the same
# directory.

from my_package import hello

hello()

Import Absolute

# Shows how to enforce and use absolute imports.
# ------------------------------------------------------------------------------
# Example script demonstrating absolute imports.
from __future__ import absolute_import
# Using absolute imports
import asyncio

# Absolute imports
from foo.api.submodule1 import func1
from foo.core.submodule2 import func2
from foo.gui.submodule3 import func3

# Call all functions
func1()
func2()
func3()

Import Relative

# Shows how to use relative imports within a package.
# -----------------------------------------------------------------------------
# Demonstrates importing modules from the current package using relative syntax.

from .foo.api.submodule1 import func1
from .foo.core.submodule2 import func2
# Relative imports are scoped to packages.

# Call the imported functions
func1()
func2()

Mymodule

# Example custom module with variables and functions
# ------------------------------------------------------------------------------
# Modules are Python files that can define variables, functions and classes.
# They allow code to be organized into reusable components. When a module is
# imported, its top-level code executes once.

PI = 3.14159


def greet(name):
    """Return a greeting string."""
    return f"Hello, {name}"


def area_circle(radius):
    """Return the area of a circle with the given radius."""
    return PI * radius * radius


if __name__ == '__main__':
    # Code executed only when running this module directly
    print(greet('module'))
    print('Area:', area_circle(2))