Core Python / Modules

Core Python / Modules#

  1. Explain the difference between a module and a package in Python.

    Both modules and packages are used to organize code, but they serve slightly different purposes.

    Module

    • A module is a single Python file that contains variables, functions, and/or classes.

    • It acts as a container for reusable code. You can import and use the contents of a module in other Python scripts or modules.

    • Modules help in organizing code logically and keeping related code together.

    • Example: If you have a file named math_operations.py containing functions for mathematical operations like addition, subtraction, etc., it can be considered a module.

    Package:

    • A package is a collection of related modules organized in a directory hierarchy.

    • It may contain an additional file named __init__.py, which indicates that the directory should be treated as a Python package.

    • Packages provide a way to structure and namespace modules hierarchically.

    • Packages can also contain sub-packages, which are directories containing their own modules and __init__.py files.

    • Example: If you have a directory named my_package containing multiple Python files (modules) such as module1.py, module2.py, and so on, along with an __init__.py file, it forms a package. You can further organize sub-packages within this package if needed.

  2. What is the purpose of the import statement in Python?

    The import statement in Python is used to bring in functionality from other modules or packages into the current script or module. Without import, your Python script or module would only have access to the built-in functions and objects provided by the Python standard library and the current script’s global namespace. This severely limits the reusability and organization of your code, making it harder to build complex applications or work with external libraries.

  3. What is the difference between import module and from module import function?

    Both import module and from module import function are ways to bring functionality from another module into your current Python script or module, but they have slightly different implications:

    import module:

    • This syntax imports the entire module into the current namespace. You need to prefix the imported functions, classes, or variables with the module name when using them.

    import math
    result = math.sqrt(25)
    

    from module import function:

    • This syntax imports specific functions, classes, or variables from the module directly into the current namespace. You can use the imported functions, classes, or variables directly without prefixing them with the module name.

    from math import sqrt
    result = sqrt(25)
    

    from module import function can make the code more concise and readable, especially when you only need a few functions or variables from a module. import module provides better clarity about the origin of the imported objects, as they are prefixed with the module name when used.

  4. How can you import a module with an alias?

    You can import a module with an alias using the as keyword. This allows you to refer to the imported module using the specified alias instead of its original name.

    import module_name as alias
    

    For many common packages, conventional aliases have been established by the the community such as pd for pandas and np for numpy. Using non-standard aliases may confuse others that read your code.

  5. How do you define functions, classes, and variables within a module?

    You can define functions, classes, and variables within a module by simply writing the corresponding Python code in the module file. Nothing special needs to be done.

  6. How do you properly document a module for others to use?

    Properly documenting a module in Python is essential for ensuring that others can understand and effectively use your code. Python provides a built-in documentation system called docstrings, which allows you to add documentation directly within your code.

    Module-Level Docstring:

    • Begin with a docstring at the top of your module file, enclosed in triple quotes (“””).

    • Provide a brief description of the module’s purpose, functionality, and usage.

    • Include any important notes or dependencies required to use the module.

    """
    Example Module
    
    This module provides various functions and classes for performing specific tasks.
    
    Usage:
    import example_module
    ...
    """
    

    Function and Class Docstrings:

    • Add docstrings immediately after the def line for functions and classes.

    • Describe the purpose of the function or class, its parameters (if any), return values, and any exceptions it may raise.

    • Provide usage examples if necessary.

    def greet(name):
        """
        Greets the user with the given name.
    
        Parameters:
        name (str): The name of the person to greet.
    
        Returns:
        str: A greeting message.
    
        Example:
        >>> greet("Alice")
        'Hello, Alice!'
        """
        return f"Hello, {name}!"
    
  7. How can variables and functions within a module be accessed from other parts of the program?

    To access variables and functions within a module from other parts of a Python program, you typically use the import statement. Then prefix the variable or function name with the module name. Sub modules/packages are specified with a period.

    You can also use from module import name so that you can directly reference the variable or function without a prefix.

  8. Discuss the pros and cons of from module import *.

    Using from module import * in Python allows you to import all names (functions, classes, variables, etc.) defined in a module directly into the current namespace. The primary advantage is the time saved in typing the prefix for each imported name with the module name. From an interactivate standpoint, this makes it easier to explore the contents as all names are directly accessible in the current namespace.

    The biggest disadvantage (and why it generally should be avoided) is namespace pollution. This can import a large number of names into the current namespace, potentially causing naming conflicts or making the code harder to understand. If the module being imported contains names that conflict with names in the current namespace, that conflict could lead to unexpected behavior.

  9. Do different python files importing the same module/package have unique or shared instances of that module/package?

    When different Python files import the same module or package, they share a single instance of that module or package. This primarily affects any shared state that may exist in that module or package.

  10. What is the purpose of the if __name__ == "__main__" idiom in Python?

    This idiom in Python is commonly used to define a block of code that should only be executed when the Python script is run directly, as opposed to being imported as a module into another script. It is similar to a main() method used in other programming languages.

  11. What is the purpose of the sys.argv list in Python, and how is it used? How do you access and iterate over the elements of sys.argv?

    The sys.argv list in Python is a list of command-line arguments passed to a Python script when it is executed from the command line. The sys module provides this functionality so that the program can access and process command-line arguments passed by the user.

    import sys
    
    # Print the name of the script
    print("Script name:", sys.argv[0])
    
    # Print command-line arguments
    # print("Arguments:", sys.argv[1:])
    
    # Iterate over command-line arguments
    for i, arg in enumerate(sys.argv[1:], 1):
        print(f"Argument {i}: {arg}")
    
    % python script.py arg1 arg2 arg3
    Script name: script.py
    Arguments: ['arg1', 'arg2', 'arg3']
    Argument 1: arg1
    Argument 2: arg2
    Argument 3: arg3