HyperLearning AI - Introduction to Python

An introductory course to the Python 3 programming language, with a curriculum aligned to the Certified Associate in Python Programming (PCAP) examination syllabus (PCAP-31-02).
https://knowledgebase.hyperlearning.ai/courses/introduction-to-python

07. Functions and Modules Part 2

https://knowledgebase.hyperlearning.ai/courses/introduction-to-python/modules/7/functions-and-modules-part-2

In this module we will formally introduce Python modules and packages, including how to write and use Python modules, how to construct and distribute Python packages, how to hide Python module entities, how to document Python modules, and Python hashbangs. Specifically we will cover:

  • Python Modules - importing modules, qualifying entities, initialising modules, writing and using modules, the name variable, Python hashbangs, and module documentation
  • Python Packages - creating packages, packages vs directories, the init file, and hiding module entities

1. Modules

1.1. Importing Modules

In [4]:
# Import our numbertools module
import numbertools
In [5]:
# Call functions from the module
print(numbertools.is_int(0.5))
print(numbertools.is_even(1_000_002))
print(numbertools.is_prime(277))
print(numbertools.is_fibonacci(12))
print(numbertools.is_perfect_square(1444))
False
True
True
False
True
In [6]:
# Access variables from the module
print(numbertools.mobius_phi)
1.618033988749895
In [7]:
# Create an alias for a module
import numbertools as nt

# Call module entities qualified with the module alias
print(nt.is_perfect_square(9801))
print(nt.mobius_phi)
True
1.618033988749895
In [8]:
# List all the function and variable names in a given module
print(dir(nt))
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'is_even', 'is_fibonacci', 'is_int', 'is_perfect_square', 'is_prime', 'math', 'mobius_phi']
In [9]:
print(dir(math))
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
In [22]:
# Import specific entities
from math import cos, pi, radians, sin, tan

# Use the specifically imported entities
print(round(cos(math.radians(90)), 0))
print(round(sin(math.radians(90)), 0))
print(round(tan(math.radians(45)), 0))
print(round(pi, 10))
0.0
1.0
1.0
3.1415926536

1.2. Module Search Path

In [ ]:
# Examine and modify sys.path
import sys

# Examine sys.path
print(sys.path)

# Append a location to sys.path
sys.path.append('/foo/bar/code')
print(sys.path)

1.5. Module Documentation

In [30]:
# Access and display a module's docstring
print(numbertools.__doc__)
Collection of tools for number testing

This module demonstrates the creation and usage of modules in Python.
The documentation standard for modules is to provide a docstring at the top
of the module script file. This docstring consists of a one-line summary
followed by a more detailed description of the module. Sections may also be
included in module docstrings, and are created with a section header and a 
colon followed by a block of indented text. Refer to
https://www.python.org/dev/peps/pep-0008/ for the PEP 8 style guide for
Python code for further information.

Attributes:
    mobius_phi (float): Module level variables are documented in
    either the ``Attributes`` section of the module docstring, or in an
    inline docstring immediately following the variable. Either form is
    acceptable, however HyperLearning AI prefer module level variables be
    documented in the module docstring. In this case, mobius_phi is a
    constant value used as part of the Mobius test to determine whether
    a given number is a Fibonacci number or not.
 

In [31]:
# Access and display a built-in module's docstring
print(math.__doc__)
This module provides access to the mathematical functions
defined by the C standard.
In [32]:
# Access and display a function's docstring
print(numbertools.is_fibonacci.__doc__)
Test whether a given number is a Fibonacci number or not.

    Tests whether a given number is a Fibonacci number or not using
    the Mobius Test.

    Args:
        num (int): The number to test whether it is a Fibonacci number

    Returns:
        bool: True if num is a Fibonacci number, otherwise False

    
In [33]:
# Access and display a built-in function's docstring
print(sin.__doc__)
Return the sine of x (measured in radians).
In [37]:
# Display help on the numbertools module
help(numbertools)
Help on module numbertools:

NAME
    numbertools - Collection of tools for number testing

DESCRIPTION
    This module demonstrates the creation and usage of modules in Python.
    The documentation standard for modules is to provide a docstring at the top
    of the module script file. This docstring consists of a one-line summary
    followed by a more detailed description of the module. Sections may also be
    included in module docstrings, and are created with a section header and a 
    colon followed by a block of indented text. Refer to
    https://www.python.org/dev/peps/pep-0008/ for the PEP 8 style guide for
    Python code for further information.
    
    Attributes:
        mobius_phi (float): Module level variables are documented in
        either the ``Attributes`` section of the module docstring, or in an
        inline docstring immediately following the variable. Either form is
        acceptable, however HyperLearning AI prefer module level variables be
        documented in the module docstring. In this case, mobius_phi is a
        constant value used as part of the Mobius test to determine whether
        a given number is a Fibonacci number or not.

FUNCTIONS
    is_even(num)
        Test whether a given number is even or not.
        
        Tests whether a given number is even or not using the modulo operator.
        
        Args:
            num (int): The number to test whether it is even
        
        Returns:
            bool: True if num is even, otherwise False
    
    is_fibonacci(num)
        Test whether a given number is a Fibonacci number or not.
        
        Tests whether a given number is a Fibonacci number or not using
        the Mobius Test.
        
        Args:
            num (int): The number to test whether it is a Fibonacci number
        
        Returns:
            bool: True if num is a Fibonacci number, otherwise False
    
    is_int(num)
        Test whether a given number is an integer or not.
        
        Tests whether a given number is an integer or not using the in-built
        isinstance() Python function, which returns True if the given object
        is of the specified type, otherwise False.
        
        Args:
            num (int): The number to test whether it is an integer
        
        Returns:
            bool: True if num is an integer, otherwise False.
    
    is_perfect_square(num)
        Test whether a given number is a perfect square.
        
        Tests whether a given number is a perfect square or not based
        on the Babylonian method for computing square roots.
        
        Args:
            num (int): The number to test whether it is a perfect square
        
        Returns:
            bool: True if num is a perfect square, otherwise False
    
    is_prime(num)
        Test whether a given number is a prime number or not.
        
        Tests whether a given number is a prime number or not, by first testing
        whether it is 0, 1, negative or not a whole number. If neither of these
        conditions are met, then the function proceeds to test whether the given
        number can be divided by the numbers from 2 to the floor division of the
        given number by 2 without a remainder. If not, then the given number is
        indeed a prime number.
        
        Args:
            num (int): The number to test whether it is a prime number
        
        Returns:
            bool: True if num is a prime number, otherwise False
    
    main(num)
        Entry point for the Number Tools application.
        
        Given a number, this function will test whether that given number
        is an integer, an even number, a prime number, a Fibonacci number
        and a perfect square.
        
        Args:
            num (int): The number to test
        
        Returns:
            None

DATA
    mobius_phi = 1.618033988749895

FILE
    /data/users/jillurquddus/digital/computing/repositories/git/working/introduction-to-python/numbertools.py


In [39]:
# Display help on a specific function
help(numbertools.is_perfect_square)
Help on function is_perfect_square in module numbertools:

is_perfect_square(num)
    Test whether a given number is a perfect square.
    
    Tests whether a given number is a perfect square or not based
    on the Babylonian method for computing square roots.
    
    Args:
        num (int): The number to test whether it is a perfect square
    
    Returns:
        bool: True if num is a perfect square, otherwise False

In [40]:
# Display help on a specifc built-in function
help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

In [38]:
# Display help on the built-in math module
help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.8/library/math
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to the mathematical functions
    defined by the C standard.

FUNCTIONS
    acos(x, /)
        Return the arc cosine (measured in radians) of x.
    
    acosh(x, /)
        Return the inverse hyperbolic cosine of x.
    
    asin(x, /)
        Return the arc sine (measured in radians) of x.
    
    asinh(x, /)
        Return the inverse hyperbolic sine of x.
    
    atan(x, /)
        Return the arc tangent (measured in radians) of x.
    
    atan2(y, x, /)
        Return the arc tangent (measured in radians) of y/x.
        
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(x, /)
        Return the inverse hyperbolic tangent of x.
    
    ceil(x, /)
        Return the ceiling of x as an Integral.
        
        This is the smallest integer >= x.
    
    comb(n, k, /)
        Number of ways to choose k items from n items without repetition and without order.
        
        Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
        to zero when k > n.
        
        Also called the binomial coefficient because it is equivalent
        to the coefficient of k-th term in polynomial expansion of the
        expression (1 + x)**n.
        
        Raises TypeError if either of the arguments are not integers.
        Raises ValueError if either of the arguments are negative.
    
    copysign(x, y, /)
        Return a float with the magnitude (absolute value) of x but the sign of y.
        
        On platforms that support signed zeros, copysign(1.0, -0.0)
        returns -1.0.
    
    cos(x, /)
        Return the cosine of x (measured in radians).
    
    cosh(x, /)
        Return the hyperbolic cosine of x.
    
    degrees(x, /)
        Convert angle x from radians to degrees.
    
    dist(p, q, /)
        Return the Euclidean distance between two points p and q.
        
        The points should be specified as sequences (or iterables) of
        coordinates.  Both inputs must have the same dimension.
        
        Roughly equivalent to:
            sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
    
    erf(x, /)
        Error function at x.
    
    erfc(x, /)
        Complementary error function at x.
    
    exp(x, /)
        Return e raised to the power of x.
    
    expm1(x, /)
        Return exp(x)-1.
        
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(x, /)
        Return the absolute value of the float x.
    
    factorial(x, /)
        Find x!.
        
        Raise a ValueError if x is negative or non-integral.
    
    floor(x, /)
        Return the floor of x as an Integral.
        
        This is the largest integer <= x.
    
    fmod(x, y, /)
        Return fmod(x, y), according to platform C.
        
        x % y may differ.
    
    frexp(x, /)
        Return the mantissa and exponent of x, as pair (m, e).
        
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(seq, /)
        Return an accurate floating point sum of values in the iterable seq.
        
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(x, /)
        Gamma function at x.
    
    gcd(x, y, /)
        greatest common divisor of x and y
    
    hypot(...)
        hypot(*coordinates) -> value
        
        Multidimensional Euclidean distance from the origin to a point.
        
        Roughly equivalent to:
            sqrt(sum(x**2 for x in coordinates))
        
        For a two dimensional point (x, y), gives the hypotenuse
        using the Pythagorean theorem:  sqrt(x*x + y*y).
        
        For example, the hypotenuse of a 3/4/5 right triangle is:
        
            >>> hypot(3.0, 4.0)
            5.0
    
    isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
        Determine whether two floating point numbers are close in value.
        
          rel_tol
            maximum difference for being considered "close", relative to the
            magnitude of the input values
          abs_tol
            maximum difference for being considered "close", regardless of the
            magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(x, /)
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(x, /)
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(x, /)
        Return True if x is a NaN (not a number), and False otherwise.
    
    isqrt(n, /)
        Return the integer part of the square root of the input.
    
    ldexp(x, i, /)
        Return x * (2**i).
        
        This is essentially the inverse of frexp().
    
    lgamma(x, /)
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x, [base=math.e])
        Return the logarithm of x to the given base.
        
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(x, /)
        Return the base 10 logarithm of x.
    
    log1p(x, /)
        Return the natural logarithm of 1+x (base e).
        
        The result is computed in a way which is accurate for x near zero.
    
    log2(x, /)
        Return the base 2 logarithm of x.
    
    modf(x, /)
        Return the fractional and integer parts of x.
        
        Both results carry the sign of x and are floats.
    
    perm(n, k=None, /)
        Number of ways to choose k items from n items without repetition and with order.
        
        Evaluates to n! / (n - k)! when k <= n and evaluates
        to zero when k > n.
        
        If k is not specified or is None, then k defaults to n
        and the function returns n!.
        
        Raises TypeError if either of the arguments are not integers.
        Raises ValueError if either of the arguments are negative.
    
    pow(x, y, /)
        Return x**y (x to the power of y).
    
    prod(iterable, /, *, start=1)
        Calculate the product of all the elements in the input iterable.
        
        The default start value for the product is 1.
        
        When the iterable is empty, return the start value.  This function is
        intended specifically for use with numeric values and may reject
        non-numeric types.
    
    radians(x, /)
        Convert angle x from degrees to radians.
    
    remainder(x, y, /)
        Difference between x and the closest integer multiple of y.
        
        Return x - n*y where n*y is the closest integer multiple of y.
        In the case where x is exactly halfway between two multiples of
        y, the nearest even value of n is used. The result is always exact.
    
    sin(x, /)
        Return the sine of x (measured in radians).
    
    sinh(x, /)
        Return the hyperbolic sine of x.
    
    sqrt(x, /)
        Return the square root of x.
    
    tan(x, /)
        Return the tangent of x (measured in radians).
    
    tanh(x, /)
        Return the hyperbolic tangent of x.
    
    trunc(x, /)
        Truncates the Real x to the nearest Integral toward 0.
        
        Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /data/apps/anaconda/anaconda3/lib/python3.8/lib-dynload/math.cpython-38-x86_64-linux-gnu.so


1.7. PYC Files

In [1]:
# Generate a byte code file of our numbertools module
import py_compile
py_compile.compile('numbertools.py')
Out[1]:
'__pycache__/numbertools.cpython-38.pyc'
In [2]:
# Generate a byte code file of our numbertools module in a custom location
py_compile.compile('numbertools.py', cfile='/tmp/numbertools.pyc')
Out[2]:
'/tmp/numbertools.pyc'

2. Packages

2.1. Importing Packages

In [4]:
# Import a module from a nested package in the Pandas library
import pandas.api.types as types
print(types.is_integer_dtype(str))
False
In [5]:
# Alternatively use from to import a specific module
from pandas.api import types
print(types.is_integer_dtype(str))
False
In [6]:
# Alternatively use from to import a specific function from a specific module
from pandas.api.types import is_integer_dtype
print(is_integer_dtype(str))
False

2.2.8. Install from Local Wheel

In [6]:
# Import our generated distribution package myutils
import myutils

# Alternatively import a specific module from a specific package
import myutils.collections.dictutils as dictutils
In [7]:
# Call one of our myutils bespoke functions
my_dict = {
    1: ['python', 3.8], 
    2: ['java', 11], 
    3: ['scala', 2.13]
}

# Convert a dictionary to a Pandas DataFrame using our user-defined dictutils.convert_to_dataframe() function
df = dictutils.convert_to_dataframe(my_dict, ['Language', 'Version'])
df.head()
Out[7]:
Language Version
1 python 3.80
2 java 11.00
3 scala 2.13