CCNA Modules and Packages Questions

37 of 112 questions · Page 2/2 · Modules and Packages · Answers revealed

76
Drag & Dropmedium

Drag and drop the steps to create a simple HTTP server using the http.server module in Python into the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Creating an HTTP server involves importing http.server, defining a handler, overriding methods, creating an HTTPServer instance, and calling serve_forever().

77
MCQmedium

A Python application needs to load a configuration file that should be placed in the same directory as the main script. The developer uses the __file__ attribute to get the script's path. Which expression correctly obtains the directory containing the main script?

A.os.path.dirname(os.path.realpath(__file__))
B.os.path.dirname(os.path.abspath(__file__))
C.os.getcwd()
D.os.path.abspath(__file__)
AnswerB

Correctly gets the absolute directory of the script.

Why this answer

Option B is correct because `os.path.abspath(__file__)` returns the absolute path of the script file, and `os.path.dirname()` extracts the directory portion. This reliably gives the directory containing the main script, regardless of whether the script was invoked with a relative or absolute path. The `__file__` attribute contains the path used to execute the script, which may be relative; `os.path.abspath()` resolves it to an absolute path before extracting the directory.

Exam trap

Python Institute often tests the distinction between `os.path.abspath()` and `os.path.realpath()`, and the trap here is that candidates may choose Option A thinking they need to resolve symlinks, but the question only asks for the directory containing the script as executed, not the canonical path after symlink resolution.

How to eliminate wrong answers

Option A is wrong because `os.path.realpath(__file__)` resolves symbolic links, which is unnecessary and can lead to a different directory than the actual script location if symlinks are involved; the question only asks for the directory containing the main script, not the real path after symlink resolution. Option C is wrong because `os.getcwd()` returns the current working directory, which is the directory from which the Python interpreter was launched, not necessarily the directory containing the script; this is a common misconception. Option D is wrong because `os.path.abspath(__file__)` returns the full path to the script file itself, not the directory; it omits the `os.path.dirname()` call needed to extract the directory component.

78
MCQmedium

Refer to the exhibit. Which of the following is the most likely cause of this error?

A.The __init__.py file in mypackage is empty.
B.There is a circular import between mypackage and mymodule.
C.mymodule.py does not exist in mypackage directory.
D.mypackage is a module file, not a package directory.
AnswerD

If mypackage is a .py file, you cannot import 'mymodule' from it as a submodule.

Why this answer

Option D is correct because the error indicates that Python cannot import 'mypackage' as a package. If 'mypackage' is a single module file (e.g., mypackage.py) rather than a directory containing an __init__.py file, Python treats it as a module, not a package. This prevents the expected package-style import of submodules like 'mymodule', causing the ImportError.

Exam trap

Python Institute often tests the distinction between a package (directory with __init__.py) and a module (single .py file), trapping candidates who assume any directory can be imported as a package without the required __init__.py marker.

How to eliminate wrong answers

Option A is wrong because an empty __init__.py file is perfectly valid and still marks the directory as a Python package; the error would not occur solely due to an empty __init__.py. Option B is wrong because a circular import typically raises an ImportError with a different traceback (e.g., partially initialized module), not the specific error shown. Option C is wrong because if mymodule.py did not exist, the error would be 'ModuleNotFoundError: No module named mypackage.mymodule', not the generic ImportError about mypackage itself.

79
MCQmedium

Inside a package 'data', there is a subpackage 'io' and a module 'utils'. Which import statement inside the 'io' subpackage correctly imports the 'helper' function from the sibling module 'utils'?

A.from ..utils import helper
B.import data.utils.helper
C.from .utils import helper
D.from data.io.utils import helper
AnswerA

Correct relative import: two dots refer to the parent package, then utils.

Why this answer

Option A is correct because the `..` prefix in a relative import refers to the parent package (`data`), and then `utils` is a sibling module of `io` within that parent package. This allows the `io` subpackage to import the `helper` function from the sibling module `utils` using `from ..utils import helper`.

Exam trap

Python Institute often tests the distinction between a single dot (`.` for same-package siblings) and double dots (`..` for parent-package siblings), causing candidates to mistakenly use `from .utils import helper` when the target module is in the parent package, not the current one.

How to eliminate wrong answers

Option B is wrong because `import data.utils.helper` is an absolute import that attempts to import a function directly, but Python requires importing the module first (e.g., `from data.utils import helper`). Option C is wrong because `from .utils import helper` uses a single dot, which refers to the current package (`data.io`), but there is no `utils` module inside `io`; it is a sibling, not a child. Option D is wrong because `from data.io.utils import helper` implies `utils` is a subpackage of `io`, but the problem states `utils` is a sibling module at the `data` package level, not inside `io`.

80
MCQmedium

Refer to the exhibit. Given the project structure, which of the following import statements in main.py would cause an ImportError?

A.from utils import strings
B.from ..utils import helpers
C.from utils import helpers
D.from utils.strings import format
AnswerB

Correct. Relative imports like '..' are allowed only inside a package; main.py is the top-level script.

Why this answer

Option B uses a relative import with '..' which is only valid inside a package (i.e., when the module is loaded as part of a package and has a __package__ attribute set). In a flat project structure where main.py is a top-level script, '..' attempts to go above the top-level package, which is not allowed and raises an ImportError. Python's import system requires that relative imports be used only within a package hierarchy.

Exam trap

Python Institute often tests the distinction between absolute and relative imports, trapping candidates who assume that '..' works in any script, when in fact relative imports are only valid inside a package and fail with an ImportError when used in a top-level script.

How to eliminate wrong answers

Option A is wrong because 'from utils import strings' is a valid absolute import that works when utils is a package (directory with __init__.py) containing a strings module; no ImportError occurs. Option C is wrong because 'from utils import helpers' is also a valid absolute import if helpers is a module or subpackage within utils; it does not cause an ImportError. Option D is wrong because 'from utils.strings import format' is a valid absolute import that imports the name 'format' from the strings module inside utils; as long as the module exists and contains that name, no ImportError occurs.

81
MCQmedium

You are a Python developer working on a project with the following structure: myapp/ __init__.py main.py modules/ __init__.py utils.py helpers.py The file main.py contains: from modules import utils from modules import helpers utils.some_function() helpers.another_function() When you run main.py, you get an ImportError: No module named 'modules'. However, the modules directory exists and both __init__.py files are present. The directory myapp is not installed as a package; you are running main.py directly from the myapp directory. What is the most likely cause and how should you fix it?

A.Move main.py to the parent directory of myapp and use 'from myapp.modules import utils' or run with 'python -m myapp.main' from the parent.
B.Add the parent directory of myapp to sys.path at the beginning of main.py.
C.Add an __all__ variable in modules/__init__.py to explicitly export the submodules.
D.Rename modules/__init__.py to something else.
AnswerA

This ensures myapp is treated as a package and imports are absolute.

Why this answer

Option A is correct because when running main.py directly, Python adds the directory containing main.py (myapp) to sys.path, not its parent. Since 'modules' is a subdirectory of myapp, Python cannot find it as a top-level module. Moving main.py to the parent directory or using the -m flag (which sets the working directory as the script's location) allows 'from myapp.modules import utils' to resolve correctly, as myapp becomes a package.

Exam trap

Python Institute often tests the distinction between running a script directly (which adds the script's directory to sys.path) versus using the -m flag (which adds the current working directory), and candidates mistakenly think that having __init__.py files alone is sufficient for any import style.

How to eliminate wrong answers

Option B is wrong because adding the parent directory of myapp to sys.path would still not make 'modules' importable as a top-level name; Python would need 'from myapp.modules import utils' or a relative import. Option C is wrong because __all__ controls what is exported with 'from module import *', not the ability to import the module itself; the ImportError occurs because 'modules' is not found as a package, not because of missing exports. Option D is wrong because renaming or removing __init__.py would break the package structure entirely, preventing Python from recognizing 'modules' as a package at all.

82
MCQhard

You are a developer at a company that builds a data processing pipeline. The pipeline consists of several Python modules organized in a package called 'pipeline'. The package structure is: pipeline/ __init__.py load.py transform.py analyze.py The pipeline is deployed on a server where Python 3.8 is installed. The server also has a globally installed package called 'pipeline' (from a different project) in the site-packages directory. When you run your scripts that import 'pipeline', you get unexpected behavior because Python is importing the wrong package. You need to ensure that your local 'pipeline' package is used instead of the global one. You cannot uninstall the global package because it is used by another application. You have the following options: A) Modify the PYTHONPATH environment variable to include the directory containing your 'pipeline' package before the site-packages directory. B) Rename your local 'pipeline' package to something else and update all imports. C) Use a virtual environment specific to your project and install your package there. D) Add an __init__.py file with a special import hook to override the global package. Which course of action is the most appropriate and reliable?

A.Use a virtual environment specific to your project and install your package there.
B.Add an __init__.py file with a special import hook to override the global package.
C.Rename your local 'pipeline' package to something else and update all imports.
D.Modify the PYTHONPATH environment variable to include the directory containing your 'pipeline' package before the site-packages directory.
AnswerA

Virtual environments provide clean isolation and are best practice.

Why this answer

Option A is correct because using a virtual environment creates an isolated Python environment where you can install your local 'pipeline' package without affecting or being affected by the globally installed package. This is the most reliable approach as it ensures that Python's import system will search the virtual environment's site-packages before the global site-packages, preventing any naming conflicts. Virtual environments are the standard Python best practice for managing project-specific dependencies and avoiding package name collisions.

Exam trap

The trap here is that candidates often assume modifying PYTHONPATH is a simple and effective solution, but Cisco tests the understanding that PYTHONPATH does not always override site-packages reliably, especially in modern Python versions, making virtual environments the only robust and recommended approach.

How to eliminate wrong answers

Option B is wrong because adding an __init__.py file with a special import hook is not a standard or reliable mechanism to override a global package; Python's import system does not support such hooks in a way that would consistently bypass the global package, and this approach is fragile and non-portable. Option C is wrong because renaming your local package is a workaround that does not solve the underlying import order issue; it also requires updating all imports across the codebase, which is error-prone and does not prevent future conflicts if another package with the same name is installed. Option D is wrong because modifying PYTHONPATH to include your local package directory before site-packages is unreliable; the order of directories in PYTHONPATH is not guaranteed to take precedence over site-packages in all Python versions or configurations, and it can be easily overridden by other environment settings or by the way Python initializes its import path.

83
MCQmedium

You are developing a Python application that processes financial transactions. The application is structured as a package named `finance`. Inside `finance`, there are subpackages: `models`, `services`, and `utils`. The `services` subpackage contains a module `validator.py` that defines a function `validate_transaction()`. This function uses a helper function `check_amount()` defined in `utils.helpers`. The package is used by multiple other projects, and you want to ensure that importing `finance` does not accidentally expose internal helper functions. You also want to allow users to easily import the main validation function via `from finance import validate_transaction`. Which of the following approaches best achieves these goals?

A.In `finance/__init__.py`, write `from . import services` and `from .services import validator`. Then users can call `finance.services.validator.validate_transaction()`.
B.In `finance/__init__.py`, write `from .services.validator import validate_transaction`. Then users can call `finance.validate_transaction()`.
C.In `finance/__init__.py`, write `from .services import validator`. Then users can call `finance.validator.validate_transaction()`.
D.In `finance/__init__.py`, write `from .utils.helpers import *` and `from .services.validator import validate_transaction`.
AnswerB

This imports only the needed function, keeping helpers private.

Why this answer

Option B is correct because it imports the `validate_transaction` function directly into the `finance` package namespace via `from .services.validator import validate_transaction` in `finance/__init__.py`. This allows users to use `from finance import validate_transaction` as desired, while keeping internal helper functions like `check_amount` in `utils.helpers` unexposed, since they are not imported into the package's top-level namespace. This approach follows the principle of explicit imports and encapsulation.

Exam trap

Python Institute often tests the distinction between importing a module versus importing a specific name from a module, and the trap here is that candidates may think importing the module (e.g., `from .services import validator`) is sufficient to allow `from finance import validate_transaction`, when in fact it only makes `finance.validator` available, not the function directly.

How to eliminate wrong answers

Option A is wrong because it only imports the `services` subpackage and the `validator` module, requiring users to call `finance.services.validator.validate_transaction()`, which does not satisfy the requirement of importing via `from finance import validate_transaction`. Option C is wrong because it imports the `validator` module into the `finance` namespace, so users would call `finance.validator.validate_transaction()` instead of `finance.validate_transaction()`, failing the desired import pattern. Option D is wrong because it uses `from .utils.helpers import *`, which exposes all names from `helpers` (including the internal `check_amount`) into the `finance` namespace, violating the goal of not accidentally exposing internal helper functions.

84
MCQhard

A developer appends a custom path to sys.path and then tries to import a function from a module: import sys; sys.path.append('/custom/libs'); from mylib import func. The import fails with ModuleNotFoundError. mylib is a directory. What is the most likely cause?

A.The import order is wrong; sys.path.append should be after the import.
B.mylib.py exists in the same directory as the script.
C.The appended path does not exist on the filesystem.
D.The mylib directory lacks an __init__.py file.
AnswerD

Without __init__.py, the directory is not recognized as a package.

Why this answer

Option D is correct because when importing from a directory (package), Python requires an `__init__.py` file (even if empty) in that directory to treat it as a package. Without it, Python does not recognize `mylib` as a package, so `from mylib import func` fails with `ModuleNotFoundError`. This is a fundamental requirement for regular packages in Python (prior to namespace packages in Python 3.3+).

Exam trap

Python Institute often tests the misconception that adding a directory to `sys.path` is sufficient to import from it, but the trap is that the directory must be a proper package with an `__init__.py` file, otherwise Python will not treat it as a module or package.

How to eliminate wrong answers

Option A is wrong because `sys.path.append` must occur before the import to add the custom path to the module search list; placing it after would have no effect, but the error here is not about order. Option B is wrong because if `mylib.py` existed in the same directory, the import would succeed (assuming the script's directory is already in `sys.path`), but the question states `mylib` is a directory, not a file. Option C is wrong because even if the appended path does not exist, Python would simply skip it during module search and continue looking elsewhere; the error would only occur if no valid path contains the module, but the core issue here is the missing `__init__.py` inside the directory.

85
MCQeasy

A programmer wants to create a package named 'analytics' with subpackages 'statistics' and 'ml'. Which directory structure correctly defines these packages?

A.analytics/, analytics/statistics/ (__init__.py), analytics/ml/ (__init__.py)
B.analytics/ (__init__.py), analytics/statistics/ (__init__.py), analytics/ml/ (__init__.py), analytics/__init__.py (file)
C.analytics/ (__init__.py), analytics/statistics/, analytics/ml/
D.analytics/ (__init__.py), analytics/statistics/ (__init__.py), analytics/ml/ (__init__.py)
AnswerD

Each directory must contain an __init__.py file to be recognized as a package.

Why this answer

In Python, a directory is recognized as a package only if it contains an `__init__.py` file (even if empty). To create the 'analytics' package with 'statistics' and 'ml' subpackages, each directory must have its own `__init__.py`. Option D correctly places `__init__.py` in all three directories: `analytics/`, `analytics/statistics/`, and `analytics/ml/`.

Exam trap

Python Institute often tests the misconception that only the top-level package needs an `__init__.py` file, or that subdirectories without `__init__.py` are still valid subpackages, leading candidates to pick option C or A.

How to eliminate wrong answers

Option A is wrong because the top-level `analytics/` directory lacks an `__init__.py` file, so Python will not treat it as a package, making subpackage imports fail. Option B is wrong because it redundantly lists `analytics/__init__.py` twice (once as a parenthesized file and once as a separate entry), which is syntactically incorrect and implies a duplicate file; the correct structure requires exactly one `__init__.py` per directory. Option C is wrong because the subdirectories `analytics/statistics/` and `analytics/ml/` do not contain `__init__.py` files, so they are not recognized as Python packages, only as ordinary directories.

86
MCQhard

A script runs: import sys; print(sys.path[0]). The output is an empty string. What does this indicate?

A.The script is being read from stdin.
B.Python was launched with the -I flag.
C.The current working directory is not in sys.path.
D.The script is running from an interactive shell.
AnswerA

When reading from stdin, sys.path[0] is empty string.

Why this answer

When a script is read from stdin (e.g., via `python < script.py` or `echo 'print(1)' | python`), Python sets `sys.path[0]` to an empty string because there is no script file path to derive the directory from. This is the documented behavior: `sys.path[0]` is the directory containing the script, or an empty string if the script is read from standard input.

Exam trap

Python Institute often tests the subtle distinction between `sys.path[0]` being empty (stdin/`-c`) versus being the script's directory (file execution), and candidates confuse this with the current working directory or the `-I` flag's effect on `sys.path`.

How to eliminate wrong answers

Option B is wrong because the `-I` flag (isolated mode) prevents `sys.path` from including the script's directory or the user site-packages, but it does not cause `sys.path[0]` to be an empty string; it would still contain the script's directory if a script file is given. Option C is wrong because the current working directory is not in `sys.path` by default in Python 3 (it was in Python 2), but `sys.path[0]` specifically refers to the script's directory, not the CWD. Option D is wrong because when running from an interactive shell, `sys.path[0]` is set to the directory of the script that started the interpreter (or an empty string if no script), but the interactive shell itself does not cause an empty string; the empty string only occurs when the script is read from stdin.

87
MCQmedium

A team uses virtual environments to manage dependencies. They need to ensure that a script runs with the exact same module versions across different environments. Which approach is best?

A.Use sys.path.append to add module directories.
B.Copy the entire virtual environment folder to other systems.
C.Include the modules in a __pycache__ directory.
D.Run pip freeze and store the output in a requirements.txt file, then use pip install -r on other systems.
AnswerD

This is the standard method for replicating environments.

Why this answer

Option D is correct because `pip freeze` outputs the exact versions of all installed packages in the current environment, and storing that output in a `requirements.txt` file allows you to reproduce the same environment on another system by running `pip install -r requirements.txt`. This ensures deterministic dependency management across different environments, which is the standard practice for reproducible builds in Python.

Exam trap

Python Institute often tests the misconception that copying the virtual environment folder (Option B) is a valid way to replicate dependencies, but the trap is that virtual environments are not portable across different operating systems or Python versions due to absolute paths and compiled extensions.

How to eliminate wrong answers

Option A is wrong because `sys.path.append` only adds directories to Python's module search path at runtime; it does not control which versions of modules are installed, nor does it ensure the same versions across environments. Option B is wrong because copying the entire virtual environment folder is platform-dependent (e.g., paths and compiled binaries may not work on different OS or Python versions) and is not a portable or recommended practice. Option C is wrong because `__pycache__` directories contain bytecode cache files (`.pyc`) that are specific to the Python interpreter version and are not meant for distributing or managing module versions; they are automatically regenerated and do not include the original source or version metadata.

88
MCQmedium

A developer is writing a package that contains multiple modules. The package should allow users to import it directly and have all commonly used functions available at the package level. For example, after `import mypackage`, the user should be able to call `mypackage.func1()` without needing to import submodules. Which is the best way to achieve this?

A.Create a wrapper function in `__init__.py` that delegates calls to the submodule functions.
B.Include `__all__` in each submodule and ensure `__init__.py` is empty.
C.In `__init__.py`, import the desired functions from the submodules, e.g., `from .submodule import func1`.
D.Define a list named `__all__` in the package's `__init__.py` that lists the functions.
AnswerC

Importing into `__init__.py` makes those names available directly on the package object.

Why this answer

Option C is correct because `__init__.py` is executed when a package is imported, and importing functions from submodules into `__init__.py` makes them directly accessible as attributes of the package object. This allows `mypackage.func1()` to work without requiring the user to import submodules explicitly, satisfying the requirement of a flat namespace at the package level.

Exam trap

Python Institute often tests the distinction between `__all__` (which controls `from package import *` behavior) and actual imports in `__init__.py` (which populate the package namespace), causing candidates to mistakenly believe that `__all__` alone makes functions accessible at the package level.

How to eliminate wrong answers

Option A is wrong because a wrapper function in `__init__.py` that delegates calls would require the user to call a function (e.g., `mypackage.func1()`) that internally dispatches to submodule functions, but this approach is unnecessarily complex and does not directly expose the submodule functions as package attributes; it also breaks direct attribute access and introspection. Option B is wrong because including `__all__` in each submodule controls what is exported when using `from submodule import *`, but an empty `__init__.py` does not import anything into the package namespace, so `mypackage.func1()` would fail with an AttributeError. Option D is wrong because defining `__all__` in `__init__.py` only controls what is exported when using `from mypackage import *`; it does not actually import the functions into the package namespace, so `mypackage.func1()` would still raise an AttributeError unless the functions are explicitly imported.

89
Multi-Selecthard

Which THREE of the following statements about Python packages and modules are true?

Select 3 answers
A.The sys.path list is read-only and cannot be modified at runtime.
B.A package must contain an __init__.py file to be importable.
C.A module is a single .py file containing Python definitions and statements.
D.The __all__ variable defines the public API of a module or package.
E.Relative imports use dots to refer to the current and parent packages.
AnswersC, D, E

This is the definition of a module.

Why this answer

Option C is correct because a module in Python is defined as a single .py file that contains Python definitions, such as functions, classes, and variables, as well executable statements. This is the fundamental unit of code organization in Python, and any .py file can be imported as a module.

Exam trap

Python Institute often tests the misconception that sys.path is immutable or that __init__.py is always mandatory, leading candidates to incorrectly mark A or B as true when they are false under current Python behavior.

90
MCQhard

Refer to the exhibit. A Python script uses the following code to load the policy. However, it fails with a JSONDecodeError. What is the most likely cause? ```python import json with open('policy.json', 'r') as f: policy = json.load(f) ```

A.The JSON file contains a trailing comma after the last element.
B.The policy variable is used before assignment elsewhere in the script.
C.The file should be opened in binary mode ('rb') instead of text mode.
D.The JSON decoder cannot handle IP addresses in strings.
AnswerA

JSON does not allow trailing commas; the comma after the second object is invalid.

Why this answer

Option A is correct because Python's json.load() strictly follows the JSON specification (RFC 7159), which does not allow trailing commas after the last element in an array or object. When the JSON file contains a trailing comma, the decoder raises a JSONDecodeError. This is a common syntax error in hand-written or poorly generated JSON files.

Exam trap

Python Institute often tests the subtle difference between Python's permissive syntax (which allows trailing commas) and the strict JSON specification, leading candidates to incorrectly assume that Python's json module would accept trailing commas.

How to eliminate wrong answers

Option B is wrong because a NameError (not JSONDecodeError) would occur if the variable 'policy' were used before assignment elsewhere; the error in the question is specifically a JSONDecodeError from json.load(). Option C is wrong because json.load() works perfectly with text mode ('r') for JSON files, as JSON is a text-based format; binary mode ('rb') is only needed for non-text data or when using json.loads() on bytes. Option D is wrong because the JSON decoder can handle any valid JSON string, including IP addresses, as they are just strings; there is no special restriction on IP addresses in the JSON specification.

91
MCQhard

A Python project uses namespace packages spread across multiple directories. The package structure is: project/ and lib/ both contain subdirectories 'mypkg/'. Each has an __init__.py file. When importing 'mypkg', which directory's contents are used?

A.Both directories are merged into a single namespace package.
B.Only the directory that appears first in sys.path is used.
C.An error is raised due to ambiguous import.
D.The last directory in sys.path overrides the previous.
AnswerB

Python's import system uses the first matching location.

Why this answer

When both directories contain an __init__.py file, they are regular packages, not namespace packages. Python's import system uses the first match in sys.path; it does not merge regular packages. Therefore, only the directory that appears first in sys.path is used, making option B correct.

Exam trap

The trap here is that candidates confuse regular packages (with __init__.py) with namespace packages (without __init__.py), assuming Python merges both regardless, when in fact the presence of __init__.py prevents merging and triggers first-found-wins behavior.

How to eliminate wrong answers

Option A is wrong because namespace packages require directories without __init__.py files; with __init__.py present, each is a regular package and Python does not merge them. Option C is wrong because Python does not raise an error for duplicate package directories; it silently uses the first one found in sys.path. Option D is wrong because Python's import order is first-found-wins, not last-overrides; the last directory in sys.path is never consulted if a match is found earlier.

92
MCQeasy

A module 'config.py' contains a variable 'settings' that is a dictionary. Another script does: from config import settings. Then the script modifies settings['key'] = 'new_value'. What happens?

A.The config module is reloaded and the change is lost.
B.The script gets a copy of the dictionary, so config.settings is unchanged.
C.The change is reflected in config.settings because it is the same object.
D.An error occurs because settings is read-only.
AnswerC

Both names refer to the same dictionary object.

Why this answer

Option C is correct because Python's import statement binds the name 'settings' in the importing module's namespace to the same dictionary object that exists in config.py. Since dictionaries are mutable, modifying settings['key'] directly mutates the shared object, and the change is visible through config.settings as well.

Exam trap

Python Institute often tests the misconception that from ... import ... creates a copy of the object, when in fact it only binds a reference to the same mutable object in memory.

How to eliminate wrong answers

Option A is wrong because Python does not automatically reload modules after an import; the module is cached in sys.modules and the change persists. Option B is wrong because from config import settings does not create a copy of the dictionary; it creates a reference to the same mutable object, so modifications affect the original. Option D is wrong because dictionary items are not read-only by default; they can be freely assigned unless explicitly protected (e.g., by a custom class or frozen dict).

93
MCQhard

A developer is creating a Python package named 'utils' and wants to control what is imported when a user writes 'from utils import *'. Which file and variable should be defined?

A.Define __all__ as a function that returns the list of modules in '__init__.py'.
B.Define __all__ = ['mod1', 'mod2'] in '__init__.py' of the 'utils' package.
C.Set the __all__ variable in the script that imports the package.
D.Define __all__ as a list of module objects in the main module 'utils.py'.
AnswerB

Standard practice to specify public modules.

Why this answer

Option B is correct because in Python, the `__all__` variable in the `__init__.py` file of a package explicitly defines the list of module names that are exported when a user writes `from utils import *`. This controls the public API of the package and prevents unintended internal modules from being imported.

Exam trap

Python Institute often tests the misconception that `__all__` can be defined in the importing script or as a function, or that it belongs in a separate module file rather than the package's `__init__.py`.

How to eliminate wrong answers

Option A is wrong because `__all__` must be a list of strings (module names), not a function that returns a list; defining it as a function would cause a TypeError when Python tries to iterate over it during the `import *` process. Option C is wrong because `__all__` must be defined inside the package's `__init__.py` (or the module itself), not in the script that imports the package; setting it in the importing script has no effect on what `from utils import *` brings in. Option D is wrong because `__all__` should be defined in the `__init__.py` file of the package, not in a separate `utils.py` main module; the package's `__init__.py` is the file Python reads when the package is imported, and `__all__` there controls the star import behavior.

94
MCQhard

In module_b.py, the developer writes: from mypackage import module_a. When running a script that imports mypackage, an ImportError occurs. Which change should solve the issue?

A.Use from .. import module_a (relative import).
B.Add 'module_a' to __all__ in mypackage/__init__.py.
C.Move module_b.py to the mypackage directory.
D.Use import mypackage.module_a instead.
AnswerA

Relative imports are the correct way to reference sibling or parent modules inside a package.

Why this answer

Option A is correct because the error occurs when module_b.py is inside the mypackage directory but uses an absolute import (from mypackage import module_a) that fails when mypackage is not on sys.path or is being executed as a script. Changing to a relative import (from .. import module_a) makes the import relative to the current module's location, allowing module_b to import module_a from its parent package without relying on the package being installed or on sys.path.

Exam trap

Python Institute often tests the distinction between absolute and relative imports in the context of package-internal scripts, where candidates mistakenly think that adding __all__ or changing the import syntax to a dotted path will fix an ImportError caused by sys.path issues.

How to eliminate wrong answers

Option B is wrong because __all__ controls what is exported when using 'from mypackage import *', but it does not affect the ability to import module_a directly; the ImportError is about the import statement itself, not about what names are exposed. Option C is wrong because module_b.py is already inside the mypackage directory (as implied by the question), and moving it would not fix the import; the issue is the import path, not the file location. Option D is wrong because 'import mypackage.module_a' is essentially the same absolute import as 'from mypackage import module_a' and would fail for the same reason if mypackage is not properly on sys.path or is being run as a script.

95
MCQhard

A package 'mypackage' has subpackages 'sub1' and 'sub2'. In sub1/__init__.py, there is: from sub2 import helper. When importing mypackage, an ImportError occurs: No module named 'sub2'. What is the most likely cause?

A.Sub2 is not installed in the Python environment.
B.Sub2 must be imported before sub1 in the package's __init__.py.
C.Sub1 should not have an __init__.py file.
D.The import should be from .sub2 import helper (relative import).
AnswerD

Relative imports are required to locate sibling packages within a package.

Why this answer

Option D is correct because when a subpackage (sub1) tries to import from a sibling subpackage (sub2) using a bare name (from sub2 import helper), Python looks for 'sub2' as a top-level module, not as a sibling within the same parent package. Since 'sub2' is not installed as a top-level module, an ImportError occurs. Using a relative import (from .sub2 import helper) explicitly tells Python to look for sub2 as a sibling package under the same parent, resolving the import correctly.

Exam trap

Python Institute often tests the distinction between absolute and relative imports in packages, trapping candidates who assume that sibling subpackages are automatically visible to each other without using dot-based relative imports.

How to eliminate wrong answers

Option A is wrong because the error 'No module named sub2' occurs even if sub2 is present in the package directory; the issue is the import path, not installation. Option B is wrong because the order of importing subpackages in the parent __init__.py does not affect how sub1 resolves its own imports; the error stems from sub1's internal import statement, not from the parent's import sequence. Option C is wrong because removing __init__.py from sub1 would prevent it from being recognized as a package, breaking all imports from it, not fixing the sibling import issue.

96
Multi-Selectmedium

Which TWO of the following are valid ways to import a module named 'math' and give it an alias 'm'?

Select 2 answers
A.from math import * as m
B.import math as m
C.import math m
D.import math alias m
E.from math import sin as m
AnswersB, E

Correct alias syntax.

Why this answer

Option B is correct because the `import ... as` syntax is the standard Python way to import a module and assign it an alias. This allows you to refer to the module's contents using the shorter alias `m` instead of the full module name `math`.

Exam trap

Python Institute often tests the distinction between `import module as alias` and `from module import name as alias`, and the trap here is that candidates may confuse the alias syntax for modules with the alias syntax for specific names, or incorrectly assume that `alias` is a valid keyword.

97
MCQhard

A developer has two separate directories on sys.path: /home/user/libs and /opt/libs. Both directories contain a subdirectory 'mypackage' without an __init__.py file. The developer wants to import a module from 'mypackage' that exists only in one of the directories. What concept allows Python to treat these two directories as a single namespace package?

A.Regular packages with __init__.py
B.sys.path merging
C.Implicit namespace packages (PEP 420)
D.Package overriding
AnswerC

This feature allows multiple directories on sys.path to collectively form a package without __init__.py.

Why this answer

Option C is correct because PEP 420 introduced implicit namespace packages, which allow multiple directories on sys.path to contribute to the same package without requiring __init__.py files. When Python encounters a directory without __init__.py, it treats it as a namespace package, merging all matching directories across sys.path into a single logical package. This enables the developer to import a module from 'mypackage' that exists in only one of the directories, as Python searches all paths and resolves the module from the first location where it is found.

Exam trap

Python Institute often tests the distinction between regular packages (with __init__.py) and implicit namespace packages (without __init__.py), and the trap here is that candidates mistakenly think sys.path merging or package overriding is the correct concept, when in fact PEP 420's implicit namespace packages are the precise mechanism that allows multiple directories to form a single package without __init__.py.

How to eliminate wrong answers

Option A is wrong because regular packages require an __init__.py file to be present, which is explicitly stated as missing in the question; using regular packages would not allow the two directories to be treated as a single package. Option B is wrong because sys.path merging is not a Python concept; sys.path is a list of directories that Python searches sequentially, but it does not merge directories into a single namespace package. Option D is wrong because package overriding is not a standard Python mechanism; Python does not override packages but instead uses the first module found on sys.path, and without __init__.py, it relies on namespace packages to combine directories.

98
MCQmedium

You maintain a Python library 'myutils' that is installed as a package in the system. The library has a submodule 'config' that reads configuration from a file. Recently, a user reported that after updating the library, their application still uses the old configuration values. They confirmed that the config file on disk has been updated. The library's __init__.py does: from .config import load_config. The user's application imports load_config from myutils and calls it each time they need configuration. What is the most likely cause of the issue?

A.The user did not restart the Python interpreter, so sys.modules still contains the old module.
B.The import statement in __init__.py is cached, so the module is not reloaded even after update.
C.The library's .pyc files were not regenerated because the .py timestamps were not updated during the install, so Python used the cached bytecode from the previous version.
D.The config module caches the configuration file contents in memory after the first read.
AnswerC

If the .py file's modification time is not newer than the .pyc file, Python uses the bytecode.

Why this answer

Option C is correct because Python caches compiled bytecode in .pyc files. If the .pyc file's timestamp is newer than the corresponding .py file, Python will use the cached bytecode without recompiling. During a package update, if the .py files' timestamps are not updated (e.g., due to a flawed installation process), Python continues to load the old .pyc, causing the old configuration-reading code to execute even though the config file on disk has changed.

Exam trap

Python Institute often tests the misconception that Python always recompiles .pyc files when the source changes, but the trap is that Python relies on file timestamps, not content hashes, so a stale .pyc can persist if the .py timestamp is not updated during installation.

How to eliminate wrong answers

Option A is wrong because the user is calling load_config each time they need configuration, not relying on a module-level cached value; restarting the interpreter would not fix stale bytecode if the .pyc is still newer than the .py. Option B is wrong because the import statement in __init__.py is not cached; Python's import system caches the loaded module object in sys.modules, but the user is importing load_config and calling it repeatedly, so the module is already loaded and the function is executed fresh each call. Option D is wrong because the question states the user confirmed the config file on disk has been updated, and the issue is that the library code itself is stale (not that the config module caches file contents in memory).

99
MCQeasy

A module 'shapes.py' defines several classes: Circle, Square, Triangle. The developer wants to allow users to import only Circle and Square when they use 'from shapes import *'. Which mechanism should be used?

A.Prefix the Triangle class with an underscore to make it private.
B.Use the import_explicit function.
C.Create an __init__.py file in the same directory.
D.Define a list variable named __all__ containing the string names 'Circle' and 'Square'.
AnswerD

__all__ explicitly lists names to export.

Why this answer

Option D is correct because the `__all__` variable in a module explicitly controls which names are exported when a client uses `from shapes import *`. By setting `__all__ = ['Circle', 'Square']`, only those two classes are imported, while `Triangle` is excluded. This is the standard Python mechanism for restricting wildcard imports.

Exam trap

Python Institute often tests the misconception that an underscore prefix makes a name truly private or that an `__init__.py` file alone controls wildcard imports from a single module, leading candidates to choose A or C instead of the correct `__all__` mechanism.

How to eliminate wrong answers

Option A is wrong because prefixing a name with an underscore (e.g., `_Triangle`) only signals that it is intended for internal use; it does not prevent `from shapes import *` from importing it — Python does not enforce privacy. Option B is wrong because there is no built-in function named `import_explicit` in Python; this is a fabricated term. Option C is wrong because an `__init__.py` file is used to mark a directory as a package and can define its own `__all__`, but it does not control imports from a single module file like `shapes.py`; the question specifies a module, not a package.

100
MCQmedium

A developer is troubleshooting an ImportError: 'No module named 'config''. The config module is located in a subdirectory 'utils' relative to the script. The script's current working directory is the parent of 'utils'. Which of the following lines, added to the script, will resolve the issue?

A.sys.path.append('utils/config.py')
B.sys.path.append('utils')
C.sys.path = os.path.join(sys.path, 'utils')
D.os.chdir('utils')
AnswerB

This adds the utils directory to the module search path.

Why this answer

The ImportError occurs because Python's module search path (sys.path) does not include the 'utils' subdirectory. Adding 'utils' to sys.path via sys.path.append('utils') tells Python to look inside that directory for modules, resolving the import. Option B is correct because it extends the search path to include the directory containing the config module, without altering the script's working directory or incorrectly appending a file path.

Exam trap

Python Institute often tests the distinction between modifying sys.path with a directory versus a file path, and the trap here is that candidates mistakenly think appending the full file path (option A) or using os.path.join on a list (option C) will work, when only a directory path appended to the list is correct.

How to eliminate wrong answers

Option A is wrong because sys.path expects directory paths, not file paths; appending 'utils/config.py' would cause Python to look for a directory named 'utils/config.py', which does not exist. Option C is wrong because sys.path is a list, not a string, so os.path.join(sys.path, 'utils') will raise a TypeError due to mixing a list with a string. Option D is wrong because os.chdir('utils') changes the current working directory to 'utils', but the script's import statement still looks for 'config' relative to the original working directory; moreover, changing the working directory can break relative file operations elsewhere in the script.

101
MCQhard

A package 'mypkg' has the following structure: mypkg/ __init__.py submod1.py submod2.py The __init__.py file contains: from . import submod1, submod2. A user runs 'import mypkg' and then 'mypkg.submod1.func()'. However, the user got an AttributeError. What is the most likely cause?

A.submod1 is actually a package, not a module, so it cannot be called with 'func()'.
B.The __init__.py should use absolute imports like 'import mypkg.submod1' to make submod1 accessible.
C.The submod1 module does not define a function named 'func'.
D.The user must also run 'from mypkg import submod1' before accessing submod1.
AnswerC

The AttributeError indicates that the attribute 'func' does not exist in submod1.

Why this answer

Option C is correct because the AttributeError indicates that the attribute 'func' was not found on the module object 'submod1'. Since the import statement in __init__.py correctly makes submod1 accessible as mypkg.submod1, the only remaining reason for the error is that submod1.py does not define a function named 'func'. The import mechanism itself is working as intended.

Exam trap

Python Institute often tests whether candidates understand that an AttributeError on a module attribute (like a function) is distinct from an ImportError or ModuleNotFoundError, leading them to incorrectly suspect the import mechanism rather than the missing definition in the module.

How to eliminate wrong answers

Option A is wrong because submod1 is a file (submod1.py) in the package directory, not a subpackage; a package would require a subdirectory with its own __init__.py. Option B is wrong because relative imports (from . import submod1) are perfectly valid and equivalent to absolute imports in this context; both make submod1 accessible as mypkg.submod1. Option D is wrong because after 'import mypkg', the __init__.py already imports submod1 into the mypkg namespace, so 'mypkg.submod1' is directly accessible without an additional import statement.

102
Multi-Selectmedium

Which TWO statements about the __init__.py file in a Python package are true?

Select 2 answers
A.It must contain at least one import statement to be valid.
B.It is mandatory for all packages, including namespace packages.
C.It prevents submodules from being imported directly.
D.It can define the __all__ list to control what is exported with 'from package import *'.
E.It is executed when the package is first imported.
AnswersD, E

Yes, __all__ can be defined there.

Why this answer

Option D is correct because the `__all__` list in `__init__.py` explicitly defines the public API of a package, controlling which names are exported when a client uses `from package import *`. This is a standard Python mechanism to prevent unintended internal modules from being exposed.

Exam trap

Python Institute often tests the misconception that `__init__.py` is mandatory for all packages, including namespace packages, and that it must contain code to be valid, when in fact it can be empty and is optional for namespace packages.

103
MCQeasy

A developer runs pip install requests. Later, they need to find out where the module is installed on the system. Which command shows the location?

A.python -c "print(requests.__path__)"
B.pip list --path
C.python -c "import requests; print(requests.__file__)"
D.pip show requests
AnswerC

__file__ contains the path of the module.

Why this answer

Option C is correct because after importing a module in Python, its `__file__` attribute contains the absolute path to the module's `.py` file (or compiled `.pyc` file). The command `python -c "import requests; print(requests.__file__)"` first imports the module, then prints the location where Python found it, which is the exact installation path on the system.

Exam trap

Python Institute often tests the distinction between module attributes (`__file__`) and package attributes (`__path__`), and the trap here is that candidates confuse `pip show` (which shows metadata) with a command that reveals the filesystem location.

How to eliminate wrong answers

Option A is wrong because `__path__` is an attribute of packages (directories with `__init__.py`), not of regular modules like `requests`; using it would raise an `AttributeError` unless the module is a namespace package. Option B is wrong because `pip list --path` is not a valid pip command; `pip list` shows installed packages but does not have a `--path` flag to display installation locations. Option D is wrong because `pip show requests` displays metadata (version, author, dependencies) but does not show the filesystem path where the module is installed.

104
MCQeasy

A Python script is written to be used both as a standalone program and as an imported module. Which condition should the script use to execute code only when run directly?

A.if __import__ == '__main__':
B.if __name__ == '__main__':
C.if __name__ == '__module__':
D.if __file__ == 'main':
AnswerB

Correctly checks if the script is the main program.

Why this answer

Option B is correct because Python sets the global variable `__name__` to `'__main__'` when the script is executed directly (e.g., `python script.py`). When the script is imported as a module, `__name__` is set to the module's name. The condition `if __name__ == '__main__':` is the standard Python idiom to guard code that should only run in the direct execution context.

Exam trap

Python Institute often tests the exact syntax `if __name__ == '__main__':` and distracts candidates with plausible-sounding but incorrect alternatives like `__import__` or `__module__`, exploiting confusion about Python's special attributes and the difference between module-level and execution-level variables.

How to eliminate wrong answers

Option A is wrong because `__import__` is a built-in function used to import modules programmatically, not a variable that indicates direct execution; comparing it to `'__main__'` is syntactically and semantically invalid. Option C is wrong because `__name__` is never set to `'__module__'`; that string has no special meaning in Python's execution model. Option D is wrong because `__file__` holds the path to the script file, not a string like `'main'`, and it is not used to determine whether the script is run directly or imported.

105
Multi-Selecthard

Which THREE of the following are recommended techniques to avoid circular imports in Python?

Select 3 answers
A.Manually check sys.modules before importing.
B.Use the __all__ variable to control what is exported.
C.Restructure the code to move shared functionality into a separate module.
D.Use lazy imports inside functions or methods.
E.Use absolute imports instead of relative imports.
AnswersC, D, E

Eliminates the circular dependency entirely.

Why this answer

Option C is correct because moving shared functionality into a separate module breaks the circular dependency chain at the import level. When two or more modules depend on each other, Python's import system may raise an ImportError or produce partially initialized modules, leading to AttributeError. Restructuring eliminates the mutual dependency by creating a common module that both original modules can import safely.

Exam trap

Python Institute often tests the misconception that __all__ or sys.modules manipulation are valid solutions for circular imports, when in fact they are either irrelevant or dangerous workarounds that do not address the root cause.

106
Multi-Selecthard

Which TWO of the following are true about importing modules using the import statement?

Select 2 answers
A.The module is executed only once on the first import.
B.Relative imports can be used in scripts executed as the main module.
C.Importing a module with a different name using 'as' creates a copy of the module.
D.Circular imports always cause an ImportError.
E.Importing a module adds it to sys.modules.
AnswersA, E

Subsequent imports retrieve the cached module.

Why this answer

Option A is correct because Python caches imported modules in the sys.modules dictionary. When a module is imported for the first time, it is executed and its code is stored; subsequent imports of the same module simply retrieve the cached object from sys.modules without re-executing the module's code. This ensures that module-level initialization runs only once, preventing side effects like repeated resource allocation or redefinition of global variables.

Exam trap

Python Institute often tests the misconception that 'import module as alias' creates a separate copy of the module, when in reality it only creates an additional reference to the same module object in sys.modules.

107
MCQeasy

A programmer wants to use the sqrt function from the math module. Which import statement is most efficient?

A.from math import sqrt
B.import math.sqrt
C.from math import *
D.import math
AnswerA

Imports only the needed function.

Why this answer

Option A is correct because `from math import sqrt` imports only the `sqrt` function directly into the current namespace, avoiding unnecessary memory usage and name collisions. This is the most efficient approach when you need only a single function from a module, as it minimizes the import overhead and keeps the namespace clean.

Exam trap

Python Institute often tests the misconception that `import module.submodule` is valid syntax, when in fact Python requires `from module import submodule` or `import module` and then attribute access; the trap here is that candidates may think `import math.sqrt` works like a package import, but `math` is a module, not a package, and `sqrt` is a function, not a submodule.

How to eliminate wrong answers

Option B is wrong because `import math.sqrt` is invalid syntax; the dot operator is used for attribute access, not for import statements, and Python will raise a SyntaxError. Option C is wrong because `from math import *` imports all names from the math module into the current namespace, which can cause unintended name clashes and wastes memory by loading functions you don't need. Option D is wrong because `import math` imports the entire module, requiring you to call `math.sqrt()` each time, which is less efficient in terms of namespace lookup and memory if you only need the `sqrt` function.

108
MCQmedium

A developer has a project structure with 'my_package/' containing '__init__.py', 'module_a.py', and 'sub_package/' (with its own '__init__.py'). They want to import function 'foo' from 'module_a' inside a script in 'sub_package' using a relative import. Which statement is correct?

A.from .module_a import foo
B.from ..module_a import foo
C.from my_package.module_a import foo
D.from ..my_package.module_a import foo
AnswerB

Two dots go to the parent package (my_package) where module_a resides.

Why this answer

Option B is correct because the script is inside 'sub_package/', which is one directory level below 'my_package/'. To import from 'module_a' (located in the parent package 'my_package'), a relative import uses '..' to go up one package level, then specifies the module name. Thus, 'from ..module_a import foo' correctly navigates the package hierarchy.

Exam trap

Python Institute often tests the distinction between relative and absolute imports, and the trap here is that candidates confuse the dot notation ('.' for current package, '..' for parent) with file system paths, leading them to pick 'from .module_a import foo' thinking it refers to the parent directory.

How to eliminate wrong answers

Option A is wrong because '.module_a' refers to a module within the same package ('sub_package'), not the parent package 'my_package'. Option C is wrong because it uses an absolute import path, which is valid but not a relative import as required by the question. Option D is wrong because '..my_package.module_a' incorrectly goes up one level and then tries to access 'my_package' again, which is already the parent package, leading to a double reference.

109
Multi-Selectmedium

Consider the following directory structure: project/ main.py pkg/ __init__.py mod1.py subpkg/ __init__.py mod2.py From main.py, you write: from pkg.subpkg import mod2 Which THREE of the following are true regarding relative imports?

Select 3 answers
A.Relative imports only work when the importing module is part of a package.
B.In mod2.py, you can use `from .. import mod1` to import mod1 from pkg.
C.In main.py, you can use `from . import pkg` to import pkg.
D.A directory must contain an __init__.py file to be a package for relative imports to function.
E.The dot notation is interpreted based on the module's __name__ and __package__ attributes.
AnswersA, B, E

They require __package__ to be set properly.

Why this answer

Option A is correct because relative imports (using dot notation like `..` or `.`) are only valid when the importing module is itself part of a package. This is because relative imports rely on the `__package__` attribute to resolve the import path; if the module is not inside a package (e.g., a top-level script), `__package__` is `None` or empty, and relative imports will raise an `ImportError`.

Exam trap

Python Institute often tests the misconception that relative imports can be used from any module, including top-level scripts, or that `__init__.py` is always mandatory for a package; the trap here is that candidates may think `main.py` can use `from . import pkg` because it is in the same directory as `pkg/`, ignoring that relative imports require the importing module to be part of a package.

110
MCQmedium

A team is developing a large Python application with multiple modules. They encounter an ImportError when module A tries to import from module B, and module B tries to import from module A. What is the most likely cause and best practice to resolve this?

A.Use 'from module import *' to bring all names into the namespace.
B.Use lazy imports (inside functions) to defer the import until runtime.
C.Restructure the code to eliminate circular dependencies by extracting shared logic into a third module.
D.Move all imports from module A to the bottom of the file.
AnswerC

Best practice; removes the circular dependency entirely.

Why this answer

Option C is correct because circular imports occur when two modules depend on each other at the top level, causing an ImportError due to incomplete module initialization. The best practice is to restructure the code to eliminate the circular dependency, typically by extracting the shared functionality into a third module that both A and B can import without mutual dependence. This approach aligns with Python's module loading mechanism, which executes a module fully before making its names available for import.

Exam trap

Python Institute often tests the misconception that moving imports or using wildcard imports can fix circular dependencies, when in fact only restructuring the code or using lazy imports (as a temporary workaround) addresses the root cause.

How to eliminate wrong answers

Option A is wrong because 'from module import *' does not resolve circular imports; it can actually worsen the problem by flooding the namespace and still triggers the same ImportError when the circular dependency is present. Option B is wrong because while lazy imports (importing inside functions) can sometimes work around circular imports by deferring the import until after both modules are initialized, it is considered a workaround rather than a best practice, and it can lead to runtime errors if the deferred import is accessed before the other module is fully loaded. Option D is wrong because moving imports to the bottom of the file does not change the order of execution; Python still processes all top-level imports before executing the rest of the module, so the circular dependency remains unresolved.

111
Multi-Selecthard

Which THREE of the following are valid ways to import a function named 'calculate' from a module named 'math_ops' located in a subpackage 'operations' of a package 'app'?

Select 3 answers
A.from app.operations.math_ops import calculate
B.import importlib; module = importlib.import_module('app.operations.math_ops'); module.calculate()
C.import app.operations.math_ops.calculate
D.from app.import operations.math_ops import calculate
E.import app.operations.math_ops; app.operations.math_ops.calculate()
AnswersA, B, E

Valid direct import of the function.

Why this answer

Option A is correct because it uses the standard Python import syntax to directly import the 'calculate' function from the 'math_ops' module, which is located in the 'operations' subpackage of the 'app' package. This is the most straightforward and recommended way to import a specific attribute from a module.

Exam trap

Python Institute often tests the distinction between importing a module versus importing an attribute from a module, and the trap here is that candidates mistakenly think 'import module.function' is valid syntax, when in fact only 'from module import function' or 'import module' (then using module.function) are correct.

112
MCQeasy

Which of the following statements about the __init__.py file in a package is true?

A.It is required for a namespace package
B.It is required for a directory to be considered a regular package
C.It cannot contain executable code
D.It is automatically generated by Python
AnswerB

Correct. Without __init__.py, the directory is treated as a namespace package (if on sys.path) or not a package at all.

Why this answer

Option B is correct because, in Python, a directory containing an `__init__.py` file is recognized as a regular package. This file can be empty or contain initialization code, and its presence is required for the directory to be imported as a package (as opposed to a namespace package). Without it, Python will not treat the directory as a regular package.

Exam trap

Python Institute often tests the misconception that `__init__.py` is always required for any package, but the trap is that namespace packages (introduced in Python 3.3) do not need it, and candidates may confuse regular packages with namespace packages.

How to eliminate wrong answers

Option A is wrong because a namespace package does NOT require an `__init__.py` file; namespace packages are implicitly created for directories that lack `__init__.py` and are used to split a package across multiple directories. Option C is wrong because `__init__.py` can contain executable code, such as package initialization logic or importing submodules, and it is often used to control what is exported via `__all__`. Option D is wrong because `__init__.py` is not automatically generated by Python; it must be created manually by the developer, though some tools or IDEs may create it as a convenience.

← PreviousPage 2 of 2 · 112 questions total

Ready to test yourself?

Try a timed practice session using only Modules and Packages questions.