Python Modules & Packages: 20 Questions with Solutions

Master Python modular programming with 20 structured questions covering modules, packages, import resolution, and namespace management.

Import Mechanics & Architecture: Explore how Python locates modules via sys.path, caches compiled bytecode in sys.modules, and organizes packages with __init__.py. See our calculator module guide, dir(), and functions.

Python Module vs. Package Architecture Infographic
Single Module (file.py) Functions, Classes, Variables Isolated File Namespace Grouped into Package Directory (pkg/) __init__.py (Initialization) Submodules: mod1.py, mod2.py Visual hierarchy contrasting Python modules with packages.

Part 1: Core Fundamentals (Q1 to Q5) 🔝

  1. Q1: What is a Python module?

    A module is a file containing Python code (.py) that defines functions, classes, and variables for code reuse and namespace isolation.

    import math
    print(type(math), math.__name__)

    Output:

    <class 'module'> math
  2. Q2: How do you import a built-in module?

    Use the import keyword followed by the module name to search directories in sys.path.

    import math
    print('Square root of 64:', math.sqrt(64))

    Output:

    Square root of 64: 8.0
  3. Q3: What is the difference between a module and a package?

    A module is a single Python file, while a package is a directory containing multiple modules and an __init__.py file.

    # my_package/ contains __init__.py and submodules
    import os
    print('Directory + __init__.py defines a package.')

    Output:

    Directory + __init__.py defines a package.
  4. Q4: How can you create and import a custom module?

    Save functions in a .py file (e.g., greet.py) and import it in your script using import greet.

    # Simulated module function
    def hello(name):
        return f'Hello, {name}!'
    print(hello('Alex'))

    Output:

    Hello, Alex!
  5. Q5: Explain the use of the import keyword.

    The import keyword locates, compiles, and executes a module, binding its namespace into the current execution scope.

    import random
    print('Random int:', random.randint(1, 10))

    Output:

    Random int: 7

Part 2: Import Syntax & Aliasing (Q6 to Q10) 🔝

  1. Q6: How do you import specific functions from a module?

    Use the from module import identifier syntax to import members directly without the module prefix.

    from math import sqrt, pi
    print('sqrt(25):', sqrt(25), '| pi:', round(pi, 2))

    Output:

    sqrt(25): 5.0 | pi: 3.14
  2. Q7: What is the purpose of using 'as' in imports?

    The as keyword creates an alias to simplify long module names and resolve local naming collisions.

    import math as m
    print('Hypot (3, 4):', m.hypot(3, 4))

    Output:

    Hypot (3, 4): 5.0
  3. Q8: How can you list all available functions in a module?

    Use the built-in dir() function to inspect attributes, variables, and methods of an imported module.

    import math
    print([f for f in dir(math) if not f.startswith('_')][:5])

    Output:

    ['acos', 'acosh', 'asin', 'asinh', 'atan']
  4. Q9: What is the role of the __init__.py file in a package?

    It marks a directory as an importable package, executes initialization code, and specifies public API exports via __all__.

    # Inside __init__.py
    __all__ = ['core', 'utils']
    print('Exported package modules:', __all__)

    Output:

    Exported package modules: ['core', 'utils']
  5. Q10: How do you access a function inside a package submodule?

    Use dot notation (e.g., import package.submodule or from package.submodule import func).

    import urllib.parse
    print(urllib.parse.quote('Python Modules'))

    Output:

    Python%20Modules

Part 3: Advanced Mechanics (Q11 to Q15) 🔝

  1. Q11: What is the difference between 'import module' and 'from module import *'?

    import module protects namespaces with explicit prefixes, whereas * dumps all symbols locally, risking naming conflicts.

    # Explicit namespaced import (best practice)
    import math
    print(math.cos(0))

    Output:

    1.0
  2. Q12: How can you reload a modified module at runtime?

    Use importlib.reload(module) from the standard library to reload changed files without restarting Python.

    import importlib, math
    print(importlib.reload(math).__name__)

    Output:

    math
  3. Q13: What happens when importing a non-existent module?

    Python raises a ModuleNotFoundError. Handle it gracefully using a try-except block.

    try:
        import missing_pkg
    except ModuleNotFoundError as err:
        print('Caught error:', err.name)

    Output:

    Caught error: missing_pkg
  4. Q14: Can you run a Python script as both a script and a module?

    Yes, using the if __name__ == '__main__': block to execute code only during direct script execution.

    if __name__ == '__main__':
        print('Executed directly as standalone script.')

    Output:

    Executed directly as standalone script.
  5. Q15: How can you check the physical location of an imported module?

    Inspect the module's __file__ attribute to retrieve its absolute filesystem path.

    import json
    print(json.__file__.endswith(('__init__.py', '.pyc')))

    Output:

    True

Part 4: Packages & Architecture (Q16 to Q20) 🔝

  1. Q16: What is the purpose of dir() when working with modules?

    dir() lists all symbols, constants, and functions exposed by a module for live interactive discovery.

    import sys
    print('sys attributes count:', len(dir(sys)))

    Output:

    sys attributes count: 92
  2. Q17: Explain the concept of relative imports in packages.

    Relative imports use dots (. for current package, .. for parent) to navigate package directories.

    # Example: from .submodule import helper
    print('Leading dot specifies relative directory level.')

    Output:

    Leading dot specifies relative directory level.
  3. Q18: How do you resolve circular imports in Python?

    Defer imports inside functions, restructure modules to extract shared types, or use top-level interface files.

    def calculate():
        import math  # Deferred import
        return math.sqrt(100)
    print(calculate())

    Output:

    10.0
  4. Q19: Can you import modules from another directory?

    Yes, by appending the external directory path to the sys.path search list at runtime.

    import sys
    sys.path.append('/custom/path')
    print('/custom/path' in sys.path)

    Output:

    True
  5. Q20: What are the advantages of organizing code into modules?

    Modularization ensures separation of concerns, high code reusability, easier testing, and scalable collaboration.

    print('Key benefits: Reusability, Maintainability, Isolation.')

    Output:

    Key benefits: Reusability, Maintainability, Isolation.

Interactive Practice & Companion Notebook 🔝

Test import syntax, experiment with module reloading, and verify circular import solutions in our companion Jupyter Notebook:

Interactive Companion Jupyter Notebook

Explore interactive code cells for all 20 modules questions, test runtime introspection with dir(), and run self-validating assertions.

View on GitHub Run in Google Colab

Frequently Asked Questions (FAQ) 🔝

Where does Python search for modules when importing?

Python searches the current script directory, PYTHONPATH directories, and standard paths in sys.path.

Is __init__.py mandatory in Python 3.3+?

Since Python 3.3, directories without __init__.py act as implicit namespace packages. However, standard packages still use it for package-level initialization.

Why avoid wildcard imports (from module import *)?

Wildcard imports pollute the local namespace, risk silently overwriting existing variables, and make code difficult to debug.

What is the difference between sys.modules and sys.path?

sys.path is the list of directory search paths. sys.modules is the internal dictionary cache storing already-loaded module objects.

Further Reading & Related Tutorials 🔝




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer