Courseiva

CCNA Modules and Packages Questions

47 questions · Modules and Packages · All types, answers revealed

1
MCQmedium

A team is developing a large application and wants to organize code into packages. Which of the following is a best practice for package design?

A.Use relative imports inside the package to avoid hardcoding the package name
B.Keep all modules in a single package for simplicity
C.Avoid using __init__.py to keep packages lightweight
D.Use absolute imports with the package name to prevent breakage when the package is moved
AnswerD

Absolute imports that start with the full top-level package name (for example `from myapp.utils.helpers import parse`) make the dependency graph explicit and easy to reason about, even when a submodule is moved within the package. Because every import references the same root, the interpreter can detect a broken path immediately and give a clear `ModuleNotFoundError` instead of silently resolving to a different local module. This clarity reduces the risk of accidental name shadowing and aligns with PEP 8's recommendation that absolute imports are the more robust, readable choice for production code. Anchoring imports to the package name ensures that refactoring tools and static analyzers can follow the actual location of each name.

Why this answer

Using absolute imports with the full package name (e.g., `from package.module import something`) ensures that the import path is explicit and independent of the module's location within the package. This prevents breakage when the package is moved or installed in a different location, as the import references the top-level package name rather than a relative path that may change. Absolute imports are the recommended style in PEP 8 for clarity and maintainability in larger applications.

Exam trap

Python Institute often tests the misconception that relative imports are always safer because they avoid hardcoding the package name, but the trap is that relative imports break when the package is moved or when modules are executed as scripts, whereas absolute imports with the package name remain stable.

How to eliminate wrong answers

Option A is wrong because relative imports (e.g., `from . import module`) can become fragile when the package structure is reorganized or when the module is executed as a script, leading to `ImportError` due to the implicit relative path. Option B is wrong because keeping all modules in a single package violates the principle of separation of concerns and makes the codebase harder to navigate, test, and reuse; packages should be organized into sub-packages based on functionality. Option C is wrong because `__init__.py` is required (in Python 3.3+ for regular packages, though namespace packages can omit it) to mark a directory as a Python package; omitting it can cause import failures unless using implicit namespace packages, which is not a best practice for a large application.

2
MCQmedium

A Python script fails with 'ModuleNotFoundError: No module named 'myapp.config''. The environment variable PYTHONPATH is not set. Which of the following is the most likely cause?

A.The module is located in a directory not included in sys.path
B.The module's __init__.py is missing
C.The module is installed in a different Python version's site-packages
D.The module has a syntax error
AnswerA

The import system resolves module names by scanning every directory listed in sys.path, which normally includes the script's own directory, entries from PYTHONPATH, and the interpreter's site-packages. If the module's parent directory is not represented anywhere in that list, Python cannot locate the file regardless of how clearly the module is named, and the import statement terminates with ModuleNotFoundError. This is the most direct and common cause of this exception, and the fix is to add the directory to sys.path, modify PYTHONPATH, or install the module properly.

Why this answer

When PYTHONPATH is not set, Python relies solely on sys.path to locate modules. sys.path includes the script's directory, standard library paths, and site-packages. If 'myapp.config' is not in any of these directories, Python raises ModuleNotFoundError. Option A correctly identifies that the module is in a directory not included in sys.path.

Exam trap

Python Institute often tests the distinction between a module not being found (ModuleNotFoundError) versus a package structure issue (missing __init__.py) or a code error (SyntaxError), tempting candidates to pick the more specific but incorrect cause.

How to eliminate wrong answers

Option B is wrong because a missing __init__.py prevents a directory from being recognized as a package, but the error 'No module named 'myapp.config'' indicates the entire module is not found, not that it fails to import from within a package. Option C is wrong because if the module were installed in a different Python version's site-packages, the error would still be ModuleNotFoundError, but the most likely cause given PYTHONPATH is unset is that the module's directory is simply not in sys.path, not a version mismatch. Option D is wrong because a syntax error in the module would cause a SyntaxError when Python tries to execute the module, not a ModuleNotFoundError.

3
MCQhard

You are a DevOps engineer managing a Python application that consists of multiple microservices. One microservice, 'data_processor', imports a shared library 'common_lib' which is also used by other microservices. The shared library is developed in a separate repository and is installed via pip in each microservice's virtual environment as an editable package (pip install -e). Recently, you updated 'common_lib' with new functions, but when you redeploy 'data_processor' (by restarting the container), the new functions are not available; the old version is still used. The container uses a Docker image built from a requirements file that specifies 'common_lib' from a Git repository. You verify that the Git commit hash in the requirements file points to the latest version. What is the most likely cause and what is the correct course of action?

A.Add the common_lib source directory to sys.path in the microservice code.
B.Rename the package in the requirements file to force a fresh install.
C.Update the commit hash or use a version tag that points to the latest, and rebuild the Docker image without using cache (--no-cache).
D.Change the Python interpreter to a different version.
AnswerC

Updating the commit hash or version tag in the dependency specification to point to the latest release, then rebuilding the Docker image with --no-cache, directly forces pip to fetch the newer revision instead of reusing cached layers. The --no-cache flag prevents Docker from reusing the old RUN pip install layer, ensuring the build environment is fresh and that the upgraded common_lib is actually installed into the image.

Why this answer

When a Docker image is built, pip installs the package from the Git repository at the commit hash specified in the requirements file. Even if the requirements file points to the latest commit, Docker's layer caching may reuse a previously built layer that contains the old version of the package. Rebuilding the image with --no-cache forces Docker to re-execute the pip install step, fetching the latest code from Git and installing the updated common_lib.

Simply restarting the container does not rebuild the image, so the old installed package persists.

Exam trap

Python Institute often tests the misconception that restarting a container or redeploying without rebuilding the image will pick up changes from a Git-based pip dependency, when in fact the package is frozen in the image layer until the image is rebuilt with a fresh pip install.

How to eliminate wrong answers

Option A is wrong because adding the common_lib source directory to sys.path would only affect runtime module resolution if the source were present in the container, but the issue is that the installed package itself is outdated; sys.path manipulation does not update the installed package. Option B is wrong because renaming the package in the requirements file would create a different package name, breaking imports and requiring code changes; it does not address the caching problem. Option D is wrong because changing the Python interpreter version does not affect which version of common_lib is installed; the package version is determined by the Git commit hash and the pip install step, not the Python version.

4
Multi-Selecthard

Which THREE of the following statements about Python's module search path are true?

Select 3 answers
A.The PYTHONPATH environment variable can be used to add custom directories to sys.path.
B.The site-packages directory is searched before the PYTHONPATH directories.
C.The directory containing the script being run is added to sys.path automatically.
D.The current working directory is always the last entry in sys.path.
E.The sys.path can be modified at runtime to change the module search path.
AnswersA, C, E

PYTHONPATH is read at startup and its entries are added to sys.path.

Why this answer

The PYTHONPATH environment variable is a standard mechanism for extending Python's module search path. When Python starts, it reads the PYTHONPATH variable and prepends its contents to sys.path, allowing users to specify additional directories where Python should look for modules before falling back to the default search order.

Exam trap

Python Institute often tests the exact order of module search path components, and the trap here is that candidates mistakenly believe site-packages is searched before PYTHONPATH, or that the current working directory is always last, when in fact the script's directory is first and PYTHONPATH precedes site-packages.

5
MCQhard

A developer notices that a custom package 'mypackage' is not being found when importing, even though it is installed in the site-packages directory. The developer suspects a conflict with another package of the same name. Which command should the developer run to diagnose the location from which Python is importing the package?

A.print(mypackage)
B.print(__file__)
C.print(mypackage.__file__)
D.import os; print(os.getcwd())
AnswerC

For an imported module, the `__file__` attribute stores the filesystem path of the source file from which the module was loaded. When `mypackage` is a package, its `__file__` points to the package's `__init__.py` file, which is exactly the location of the package on disk in most ordinary cases. This is the standard, programmatic way to determine where a package or module resides, making this option correct.

Why this answer

`mypackage.__file__` returns the filesystem path from which the module was loaded, allowing the developer to see exactly which `mypackage` Python is using. This directly reveals if the wrong package (e.g., from a different location or a conflicting installation) is being imported instead of the intended one.

Exam trap

The trap here is that candidates often confuse `__file__` (which gives the current script's path) with `module.__file__` (which gives the imported module's path), or they assume `print(mypackage)` will show the path directly, when in fact it may only show a module representation without the full path in all contexts.

How to eliminate wrong answers

Option A is wrong because `print(mypackage)` will print a string representation of the module object (e.g., `<module 'mypackage' from '/path/to/...'>`), but it does not reliably show the file path in all Python versions or environments, and it is not the standard diagnostic command. Option B is wrong because `print(__file__)` prints the path of the current script, not the imported package, so it provides no information about where `mypackage` is located. Option D is wrong because `print(os.getcwd())` prints the current working directory, which is unrelated to the import resolution path for installed packages.

6
MCQmedium

A developer has a module 'config.py' with the following content: # config.py import os DATABASE_URL = os.getenv('DATABASE_URL', 'localhost') Another module 'app.py' imports config and uses DATABASE_URL. During testing, the environment variable is set correctly, but the import still uses the default value 'localhost'. What is the most likely reason?

A.The import statement in app.py is placed inside a function, so it is not executed.
B.The module was imported using 'from config import DATABASE_URL' which creates a separate copy.
C.The environment variable is only read when the function is called, not at import time.
D.Python caches modules; config.py was imported earlier without the environment variable, and the cached version is reused.
AnswerD

Python records every imported module in sys.modules, and a later import of the same module simply fetches that cached object instead of re-executing the file. If config.py was imported earlier in the same interpreter session before the environment variable was set, its module-level code—including the os.getenv call—has already run and stored a stale default. All subsequent imports, whether 'import config' or 'from config import DATABASE_URL', see that cached module and its fixed value, so the code is not re-executed.

Why this answer

Python caches imported modules in `sys.modules`. If `config.py` was imported earlier in the test session (e.g., during test discovery or another import) before the environment variable `DATABASE_URL` was set, the cached module would retain the default value `'localhost'`. Subsequent imports, even after setting the environment variable, reuse the cached module, so `os.getenv('DATABASE_URL', 'localhost')` is not re-evaluated.

Exam trap

Python Institute often tests the misconception that `from module import name` creates an independent copy, when in fact it only binds a reference to the same object, and the real issue is Python's module caching and the timing of environment variable reads.

How to eliminate wrong answers

Option A is wrong because placing an import inside a function does not prevent its execution; the import is executed when the function is called, and the module is still cached. Option B is wrong because `from config import DATABASE_URL` creates a local name binding to the same object, not a separate copy; the issue is about the value at import time, not copying. Option C is wrong because `os.getenv` is called at import time (when the module is first loaded), not when a function is called; the environment variable is read once during module initialization.

7
Multi-Selectmedium

Which TWO of the following are valid ways to import a function 'foo' from a module 'bar' that is located in a package 'mypackage'?

Select 2 answers
A.from mypackage import bar.foo
B.from mypackage.bar import foo
C.import mypackage.bar; then use bar.foo
D.from . import bar.foo
E.import mypackage.bar.foo
AnswersB, C

Correct absolute import.

Why this answer

The syntax `from mypackage.bar import foo` directly imports the function `foo` from the module `bar` within the package `mypackage`. This is the standard Python import statement for importing a specific attribute from a submodule.

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 `from mypackage import bar.foo` is valid because they confuse it with the valid `from mypackage.bar import foo` syntax.

8
MCQhard

You are a developer for a data science team. The team uses a shared module 'utilities' located at /team/shared/utilities.py. This module is not part of any package, and they want to import it from various project scripts without copying the file. Some projects are in /home/user/proj_A/ and others in /var/data/proj_B/. Currently, each script manually adds /team/shared/ to sys.path using sys.path.insert(0, '/team/shared/'). This works but is repetitive. The team wants a cleaner solution that also works when the script is run from different working directories. They consider creating a package 'utilities' by adding an __init__.py to the directory and using relative imports. However, the module currently uses absolute imports for some external libraries. What is the best course of action to allow clean imports of utilities from any location while minimizing changes to the module itself?

A.Create an empty __init__.py in /team/shared/ to make it a namespace package.
B.Set the PYTHONPATH environment variable to include /team/shared/ in the shell profile.
C.Place a .pth file in the site-packages directory that points to /team/shared/.
D.Convert utilities.py into a package by adding __init__.py and using relative imports inside.
AnswerB

Setting PYTHONPATH in the shell profile prepends /team/shared/ to the module search path (sys.path) for every Python process spawned from that shell. This allows `import utilities` to resolve cleanly without altering the module's internals, placing the shared directory in a well-known environment variable rather than hard-coding it into each script. It is minimal, reversible, and does not touch the Python installation or require packaging changes.

Why this answer

Setting the PYTHONPATH environment variable to include /team/shared/ is the best solution because it automatically adds that directory to the module search path for all Python scripts without modifying the module itself or requiring repetitive code. This approach works regardless of the current working directory and preserves the module's existing absolute imports. Other options either do not add the directory to the search path, require modifying the module, or are more complex to implement.

Exam trap

A common mistake is to think that adding an __init__.py file makes a directory importable from anywhere. In reality, __init__.py only marks a directory as a Python package, but the directory must already be in the module search path (sys.path) to be imported. Without PYTHONPATH or sys.path manipulation, the package is not discoverable from arbitrary locations.

How to eliminate wrong answers

Option A is wrong because creating an empty __init__.py in /team/shared/ would make it a regular package, not a namespace package, and would not automatically add the directory to the module search path; scripts would still need to modify sys.path or rely on PYTHONPATH. Option C is wrong because placing a .pth file in site-packages adds the directory to sys.path only for the specific Python installation where site-packages resides, which may not be portable across different environments or projects, and it requires administrator privileges. Option D is wrong because converting utilities.py into a package by adding __init__.py and using relative imports would require rewriting the module to use relative imports, which contradicts the goal of minimizing changes and could break existing absolute imports for external libraries.

9
Multi-Selecteasy

Which TWO statements about the 'from package import *' statement are correct?

Select 2 answers
A.It imports the package itself as a module.
B.Without __all__, it imports all public names from the package's __init__.py and all submodules.
C.It imports all submodules of the package by default.
D.If __all__ is defined in __init__.py, only the names in __all__ are imported.
E.The behavior can be customized by defining the __all__ list in __init__.py.
AnswersD, E

When `__all__` is defined in the package's `__init__.py`, `from package import *` imports exactly the names contained in that list. Any name not present in `__all__` is ignored, even if it is a public variable, function, or a submodule also defined in the package. This explicit list overrides the default underscore-filtering behavior and gives the package author precise control over the subset of the package's API that is exposed to star imports.

Why this answer

When `__all__` is defined in a package's `__init__.py`, the `from package import *` statement imports only the names listed in that `__all__` list. This is the explicit mechanism Python provides to control the public API of a package when using the wildcard import syntax.

Exam trap

The PCAP exam often tests the misconception that `from package import *` automatically imports all submodules, when in fact it only imports names from the package's `__init__.py` (or those listed in `__all__`), and submodules must be explicitly imported or listed to be included.

10
MCQhard

A user wants to ensure that a custom module 'mymod' located at '/home/user/custom' takes precedence over a standard library module with the same name. Which operation on sys.path should be performed?

A.sys.path.replace('/', '/home/user/custom')
B.sys.path.append('/home/user/custom')
C.sys.path.insert(0, '/home/user/custom')
D.sys.prefix = '/home/user/custom'
AnswerC

insert(0, '/home/user/custom') places the custom directory at the very beginning of sys.path, making it the first location searched by the import machinery. This guarantees that modules in that directory take precedence over identically named modules found later in the path, including the standard library and site-packages. It also avoids issues with the working directory or other early entries, which is why insert(0, ...) is the conventional idiom for local module overrides.

Why this answer

`sys.path.insert(0, '/home/user/custom')` adds the custom module's directory to the very beginning of the module search path. Python's import system scans `sys.path` in order, so placing the custom directory first ensures that `mymod` is found there before any standard library or site-packages directory that might contain a module with the same name.

Exam trap

Python Institute often tests the distinction between `insert(0, ...)` and `append(...)`, knowing that many candidates mistakenly think adding a path anywhere in `sys.path` will override standard modules, but only insertion at the beginning achieves that precedence.

How to eliminate wrong answers

Option A is wrong because `sys.path.replace('/', '/home/user/custom')` is not a valid method on a list; `replace` is a string method and would raise an AttributeError. Option B is wrong because `sys.path.append('/home/user/custom')` adds the directory to the end of the list, so the standard library module (which is typically found earlier in `sys.path`) would still take precedence. Option D is wrong because `sys.prefix` is a read-only attribute that points to the Python installation directory; assigning to it does not affect the module search path and would raise an AttributeError or be ignored.

11
Multi-Selecthard

Which THREE factors influence Python's module search path (sys.path)?

Select 3 answers
A.The HOME environment variable
B.The current working directory at runtime
C.The site-packages directory where pip installs packages
D.The directory containing the script being executed
E.The PYTHONPATH environment variable
AnswersC, D, E

Appended when site module is processed.

Why this answer

The site-packages directory is automatically included in sys.path by the site module during Python's initialization. This directory is the default location where pip installs third-party packages, making them importable without manual path manipulation.

Exam trap

Python Institute often tests the distinction between the current working directory at runtime and the directory containing the script being executed, leading candidates to incorrectly assume the working directory is always searched for modules.

12
MCQeasy

A Python script uses a third-party library 'requests'. The developer wants to ensure that the exact version 2.25.1 is installed in the project's environment. Which tool and command should be used?

A.pip install requests
B.pip install requests==2.25.1
C.pip3 install requests==2.25.1
D.pip instll requests==2.25.1
AnswerB, C

This command correctly uses the pip package manager with an explicit version specifier. The == operator, an exact version pin defined by PEP 440, tells pip to install precisely requests 2.25.1 from PyPI, bypassing any newer or older release. This ensures reproducible dependency behavior across different machines and deployment stages.

Why this answer

Both options B and C are correct because they use the standard pip syntax for pinning a specific version: `package==version`. The command `pip install requests==2.25.1` (B) works on systems where `pip` is linked to Python 3, while `pip3 install requests==2.25.1` (C) explicitly invokes the Python 3 version of pip. Both achieve the same result—installing requests exactly version 2.25.1.

Option A fails to specify a version, and option D contains a typo ('instll') that will fail.

Exam trap

A common pitfall is assuming that `pip3` is incorrect or non-standard. In reality, both `pip` and `pip3` are valid commands for Python 3 environments; the key is the version-pinning syntax (`==`). The question tests whether the candidate recognizes the correct syntax for specifying an exact version, not the distinction between `pip` and `pip3`.

How to eliminate wrong answers

Option A is wrong because `pip install requests` installs the latest available version of the library, not the exact version 2.25.1, which fails the requirement for version pinning. Option C is wrong because `pip3` is simply an alias for `pip` on many systems (or a Python 3-specific variant) and does not change the version specification; the command is functionally identical to option B, but the question asks for the correct tool and command, and `pip` is the standard tool name. Option D is wrong because `pip instll` contains a typo ('instll' instead of 'install'), which would cause the command to fail with a 'command not found' error.

13
MCQmedium

During development, a programmer modifies a module that is already imported in the current Python session. To see the changes without restarting the interpreter, which function from the importlib module should be called?

A.reload()
B.reload_module()
C.importlib.reload()
D.importlib.import_module()
AnswerC

This is the correct way to reload a module in Python 3. It takes a module object (already imported) and re-executes its source code, updating the module's attributes in place. It is particularly useful during development to pick up changes without restarting the interpreter. Note that it returns the updated module object, and other references to the old module still point to the same object (since it mutates in place).

Why this answer

`importlib.reload()` is the official Python function to re-import a previously imported module, applying any changes made to its source code without restarting the interpreter. It is part of the `importlib` module and is the recommended way to reload modules in Python 3.

Exam trap

Python Institute often tests the distinction between the Python 2 built-in `reload()` and the Python 3 `importlib.reload()` syntax, and candidates mistakenly choose the bare `reload()` option without realizing it is no longer a built-in function.

How to eliminate wrong answers

Option A is wrong because `reload()` is not a standalone built-in function; in Python 2 it existed as a built-in, but in Python 3 it was moved to `importlib` and must be called as `importlib.reload()`. Option B is wrong because `reload_module()` is not a valid function in the `importlib` module; the correct function name is `reload()`. Option D is wrong because `importlib.import_module()` is used to import a module programmatically, not to reload an already imported module; it does not update the existing module object in memory.

14
MCQeasy

A team is using a shared Python environment where multiple projects have conflicting dependencies. Which approach is the best practice to isolate project dependencies?

A.Create a virtual environment using 'python -m venv' and install dependencies inside it.
B.Manually modify sys.path in each script to include different package directories.
C.Install all dependencies in the system-wide site-packages directory.
D.Install all packages using 'pip install --user' to avoid system conflicts.
AnswerA

Using 'python -m venv' creates an isolated environment with its own Python binary and site-packages directory, allowing each project to install exactly the dependencies and versions it needs without interfering with other projects. This is the standard, built-in best practice for managing project dependencies in a shared Python environment, and it also makes it easy to generate a reproducible requirements.txt for teammates.

Why this answer

Using `python -m venv` creates an isolated virtual environment with its own `site-packages` directory, preventing dependency conflicts between projects. This is the standard best practice recommended by the Python Packaging Authority (PyPA) for managing project-specific dependencies without affecting the system-wide Python installation.

Exam trap

The trap here is that candidates may think `pip install --user` provides isolation similar to a virtual environment, but it only separates user-level from system-level packages, not between projects, so it fails to solve the core problem of conflicting dependencies across multiple projects.

How to eliminate wrong answers

Option B is wrong because manually modifying `sys.path` in each script is fragile, error-prone, and does not isolate dependencies at the package level—it only alters the module search path, leaving the global environment unchanged and still susceptible to version conflicts. Option C is wrong because installing all dependencies in the system-wide `site-packages` directory directly causes the very conflicts the team is trying to avoid, as different projects may require different versions of the same package. Option D is wrong because `pip install --user` installs packages in the user-specific `site-packages` directory (e.g., `~/.local/lib/pythonX.Y/site-packages`), which is shared across all projects run by that user, so it does not provide per-project isolation and can still lead to dependency conflicts.

15
MCQmedium

You are developing a package 'analytics' that contains subpackages 'stats' and 'ml'. The __init__.py of 'analytics' imports a function 'normalize' from 'analytics.stats'. When a user runs `import analytics`, they get an ImportError. Which change ensures the package imports correctly?

A.Change the import to: from stats import normalize
B.Add sys.path.append('.') before the import in __init__.py
C.Change the import in analytics/__init__.py to: from .stats import normalize
D.Move the import statement to the stats/__init__.py file
AnswerC

`from .stats import normalize` is a relative import: the leading dot tells CPython's import machinery to start from the current package, `analytics`, and resolve `.stats` as `analytics.stats` (PEP 328). This works regardless of the absolute `sys.path` layout, whether `analytics` is installed as a package or invoked from a script, and it avoids name collisions with any unrelated top-level `stats` module. Since the statement appears in `analytics/__init__.py`, `.stats` is unambiguous and correctly loads the sibling submodule, making `normalize` available as `analytics.normalize`.

Why this answer

It uses an explicit relative import (`from .stats import normalize`), which is the proper way to import from a subpackage within a package. Absolute imports like `from analytics.stats import normalize` can fail if the package's parent directory is not in `sys.path`, which is common when running scripts directly. Relative imports resolve correctly based on the package structure, ensuring the import works regardless of how the package is invoked.

Exam trap

Python Institute often tests the distinction between absolute and relative imports in packages, and the trap here is that candidates mistakenly think absolute imports like `from analytics.stats import normalize` are always safe, not realizing they depend on the package being installed or the parent directory being in `sys.path`.

How to eliminate wrong answers

Option A is wrong because `from stats import normalize` uses an absolute import without the package prefix, which will look for a top-level module named `stats` rather than the subpackage `analytics.stats`, causing a ModuleNotFoundError. Option B is wrong because `sys.path.append('.')` adds the current working directory to the module search path, which is unreliable and does not guarantee that the package's parent directory is in `sys.path`; it also violates best practices by modifying `sys.path` in `__init__.py`. Option D is wrong because moving the import to `stats/__init__.py` would not make `normalize` available at the `analytics` package level when a user runs `import analytics`; the import must be in `analytics/__init__.py` to be part of the package's namespace.

16
MCQeasy

A developer creates a package named 'mypkg' with an __init__.py file. Inside the package, there is a module 'utils.py'. Which of the following is the correct way to import the function 'helper' from 'utils' from outside the package?

A.import mypkg.utils.helper
B.import mypkg; mypkg.utils.helper
C.from mypkg.utils import helper
D.from mypkg import utils.helper
AnswerC

This is the correct and idiomatic form because it explicitly names the submodule `utils` and the object `helper` in the `from ... import ...` syntax. The statement `from mypkg.utils import helper` tells Python to load `mypkg/utils` (the submodule) and then extract the attribute `helper` from that module's namespace, binding it locally as `helper`. This is the standard approach for importing a function or variable from a submodule directly, avoiding the need for dotted attribute chains.

Why this answer

It uses the standard Python syntax for importing a specific name from a submodule within a package: `from package.module import name`. This directly imports the `helper` function into the current namespace, making it callable without any prefix. The `__init__.py` file marks `mypkg` as a package, and `utils.py` is a module inside it, so `from mypkg.utils import helper` is the proper way to access `helper` from outside the package.

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 confuse the `import` statement (which only accepts modules/packages) with the `from ... import` statement (which can import any object), leading them to choose Option A or D.

How to eliminate wrong answers

Option A is wrong because `import mypkg.utils.helper` attempts to import a module named `helper`, but `helper` is a function, not a module; Python's import system only supports importing modules or packages, not individual objects like functions or classes, via the `import` statement. Option B is wrong because `mypkg.utils.helper` is not a valid attribute access after `import mypkg`; `import mypkg` only imports the top-level package, and to access `utils` you would need to import `mypkg.utils` explicitly (e.g., `import mypkg.utils`), otherwise `mypkg.utils` is undefined. Option D is wrong because `from mypkg import utils.helper` uses dot notation in the import name, which is invalid syntax; the `from ... import` statement expects a single module or a comma-separated list of names, not a dotted path to an attribute.

17
MCQmedium

Your company has two separate Python packages: 'app' and 'lib'. They are maintained by different teams. 'app' depends on 'lib', but 'lib' is still under development and its API changes frequently. To avoid breaking 'app', the team decides to use a virtual environment and install a specific version of 'lib'. However, during development, they need to test 'app' with the latest 'lib' changes from the Git repository. The current workflow is: (1) activate virtual env, (2) install 'lib' from local source using `pip install -e /path/to/lib`. This installs 'lib' as a development package. But one developer reports that after pulling latest 'lib' changes, importing 'lib' in 'app' still uses the old version even after re-running pip install -e. What is the most likely reason?

A.Python caches imported modules in sys.modules, so importing again does not reload the module from disk.
B.The package 'lib' is being imported as a namespace package, so changes are not picked up.
C.The .pyc files are not being invalidated because the timestamps are not updated.
D.The editable install may still point to an old copy of the library if the source directory was moved or if there is a stray .egg-link file.
AnswerD

An editable install for 'lib' registers the source directory via a .pth file or an .egg-link file, which adds that directory to sys.path. If the source directory was moved after the editable install, the recorded path becomes stale; alternatively, a leftover .egg-link from an earlier install can point to the old location. Re-running pip install -e should update this, but if it happened before the move or was interrupted, the import mechanism will still reference the old copy, so changes in the current directory are ignored.

Why this answer

The most likely reason is D. When using `pip install -e` (editable install), pip creates a special `.egg-link` file (or similar pointer) in the site-packages directory that points to the source directory. If the source directory was moved, renamed, or if a stale `.egg-link` file remains from a previous install, pip may still reference the old location, causing the old version to be imported even after re-running the install command.

This is a known subtlety of editable installs, especially when the source code is managed under version control and the directory structure changes.

Exam trap

Python Institute often tests the subtle difference between a stale import cache (sys.modules) and a stale install pointer (editable install link), leading candidates to incorrectly choose the caching option when the real issue is a broken or outdated path reference in the development install.

How to eliminate wrong answers

Option A is wrong because Python's `sys.modules` cache only affects modules already imported in the current interpreter session; re-running `pip install -e` and then starting a fresh Python process would not be affected by this cache. Option B is wrong because namespace packages are a different concept (PEP 420) and do not relate to the failure to pick up changes after an editable install; the issue is about the install pointer, not the package type. Option C is wrong because `.pyc` file invalidation is based on source file timestamps or hash comparison, and `pip install -e` does not modify `.pyc` files; the problem is that the import system is loading from a different location entirely, not that bytecode is stale.

18
MCQmedium

Refer to the exhibit. A script executes 'from mypackage import *'. Which functions are available in the global namespace?

A.Only func from module_a
B.It raises an ImportError because __all__ should contain function names
C.None, because __all__ lists modules, not functions
D.func from both module_a and module_b
AnswerC

Correct. __all__ defines what names are imported; here it imports the modules, so functions remain in the module namespace.

Why this answer

When `from mypackage import *` is executed, Python looks for the `__all__` list in the package's `__init__.py` file. In this exhibit, `__all__` is defined as `['module_a', 'module_b']`, which are module names, not function names. The `import *` statement imports the modules listed in `__all__` into the global namespace, not their individual functions.

Therefore, `func` from either module is not directly available; you would need to reference them as `module_a.func` or `module_b.func`.

Exam trap

The trap here is that candidates often assume `__all__` must contain function or variable names, but it can also list submodule names, and `import *` only imports those listed names—not their nested contents—into the global namespace.

How to eliminate wrong answers

Option A is wrong because `func` from `module_a` is not directly imported into the global namespace; only the module `module_a` itself is imported. Option B is wrong because `__all__` can contain module names or attribute names; it does not raise an `ImportError` when it contains module names—it simply imports those modules. Option D is wrong because `func` from both modules is not directly available; only the modules `module_a` and `module_b` are imported into the global namespace.

19
MCQeasy

A Python script imports the module 'my_module'. The developer wants to ensure that when the script is run directly, it executes a specific function, but when imported as a module, that function is not executed. Which code snippet achieves this?

A.if __name__ == '__main__': run()
B.if __name__ == '__main__': run()
C.if os.environ.get('RUN_MAIN'): run()
D.if sys.argv[0] == 'my_module': run()
AnswerA, B

This is the canonical Python idiom for conditional execution. The interpreter assigns the special variable __name__ the value '__main__' only when the source file is run directly as the main program (e.g., `python my_module.py`). When the file is imported as a module, __name__ becomes the module's fully qualified name, so the equality check fails and run() is not invoked, allowing safe import without side effects.

Why this answer

Both options A and B are correct because they are identical and represent the standard Python idiom `if __name__ == '__main__': run()`. When the script is run directly, Python sets `__name__` to `'__main__'`, triggering the function. When imported, `__name__` is the module name, so the function is not executed.

Options C and D are incorrect: C relies on an environment variable that is not standard, and D checks `sys.argv[0]` which is the script path, not the module name.

Exam trap

Python Institute often tests the distinction between `__name__` and `sys.argv` or environment variables, trapping candidates who confuse the script's filename with the module's name or who think an external flag is needed to control execution.

How to eliminate wrong answers

Option A is wrong because it is identical to option B and not a distinct code snippet; in the context of the question, both A and B are the same correct answer, but only one can be selected. Option C is wrong because `os.environ.get('RUN_MAIN')` checks for an environment variable that is not automatically set by Python; this would require manual configuration and does not reflect the standard import-time vs. run-time behavior. Option D is wrong because `sys.argv[0]` contains the script name or path used to invoke the interpreter, not the module name; it would never equal `'my_module'` when the script is imported, and it fails to distinguish between direct execution and import.

20
MCQhard

A company has a large Python application that uses multiple packages from different directories. The application's main entry point is at /opt/app/main.py. There is a package 'common' located at /opt/app/common/ and another package 'services' at /opt/app/services/. Both packages have __init__.py files. Additionally, there is a third-party package 'utils' installed in the system site-packages. Recently, a developer added a new module 'helpers.py' to the 'common' package. When trying to import 'common.helpers' from a script inside 'services', an ImportError is raised: 'No module named common.helpers'. However, importing 'common' itself works. The sys.path includes /opt/app/ and the site-packages. What is the most likely cause of the import failure?

A.The 'helpers.py' file was added after the Python interpreter started, and sys.modules caching prevents new imports.
B.There is another 'common' package elsewhere in sys.path that shadows the intended one, and the shadowed package does not have a 'helpers' submodule.
C.The PYTHONPATH environment variable is not set, so the /opt/app/ directory is not searched.
D.The 'common' package itself is already imported and cached, so adding a new module does not become visible.
AnswerB

This is the correct explanation. Python searches the directories and zip files listed in sys.path in order, and for a dotted import like 'common.helpers', it looks for a package (a directory with __init__.py) named 'common' in each path entry. If an earlier sys.path entry contains a different 'common' package that lacks a 'helpers' submodule, Python imports that shadowing package and then attempts to find 'helpers' within it, raising ModuleNotFoundError before ever reaching the intended /opt/app/common/ package. This is a classic path-shadowing bug that causes the real file to be completely ignored.

Why this answer

The most likely cause is that a different 'common' package (without a 'helpers' submodule) appears earlier in sys.path and shadows the intended /opt/app/common/ package. Since sys.path includes /opt/app/ and site-packages, if a 'common' package exists in site-packages or another directory listed before /opt/app/, Python will import that shadowed package instead, and it lacks the newly added 'helpers' module. This explains why importing 'common' succeeds (the shadowed package exists) but 'common.helpers' fails.

Exam trap

Python Institute often tests the subtlety that a package can be shadowed by another package with the same name earlier in sys.path, leading to successful import of the parent but failure for submodules that exist only in the intended package.

How to eliminate wrong answers

Option A is wrong because Python does not automatically cache modules based on file modification time; sys.modules caching only prevents re-importing a module that was already imported, but it does not prevent importing a newly added module if the package was not previously imported. Option C is wrong because the sys.path already includes /opt/app/ (as stated), so PYTHONPATH is not required for that directory to be searched. Option D is wrong because even if 'common' was previously imported, Python's import system checks for new submodules by searching the package's __path__ on disk, not just sys.modules; the issue is not caching but a shadowing conflict.

21
MCQmedium

A developer creates a package 'mypackage' with the following structure: mypackage/ __init__.py module1.py module2.py The __init__.py contains: from mypackage.module1 import func1 from mypackage.module2 import func2 __all__ = ['func1', 'func2'] In a separate script, the developer writes: from mypackage import * print(func1()) This works as expected. However, when the developer runs the same script from a different directory (not the one containing mypackage), the import works but the script prints an error that func1 is not defined. What could be the problem?

A.The current working directory is not in sys.path, so the package cannot be found.
B.The __all__ variable hides func1 because it does not include it, but it does.
C.The mypackage directory lacks proper __init__.py (maybe it is not present or invalid), causing it to be treated as a namespace package, and the __init__.py is never executed.
D.The imports in __init__.py are relative imports and fail when run from a different directory.
AnswerC

For a directory to be a regular package, Python requires a valid `__init__.py`; when that file is missing, Python 3.3+ treats the directory as a namespace package. A namespace package executes no initialization code, so the `from mypackage.func1 import func1` lines that would normally populate the package namespace never run. The package is still importable, but it appears empty — exactly matching the failure to find `func1` while `import mypackage` succeeds.

Why this answer

If the `mypackage` directory is found but its `__init__.py` is missing, invalid, or not executed (e.g., due to being a namespace package in Python 3.3+), the `from mypackage import *` statement will not trigger the imports defined in `__init__.py`. Consequently, `func1` and `func2` are never bound in the package namespace, leading to a `NameError` when the script tries to call `func1()`. This scenario occurs when the package is located via `sys.path` but the `__init__.py` is not properly processed, often because the directory is treated as a namespace package (PEP 420) rather than a regular package.

Exam trap

The PCAP exam often tests the distinction between regular packages (with `__init__.py`) and namespace packages (without `__init__.py` in Python 3.3+), trapping candidates who assume that a directory containing a package structure always executes its `__init__.py` regardless of file presence or validity.

How to eliminate wrong answers

Option A is wrong because the problem states that the import works (i.e., the package is found), so the current working directory must be in `sys.path` or the package is accessible via another path entry; the error occurs after import, not during it. Option B is wrong because `__all__` explicitly includes `'func1'` and `'func2'`, so it does not hide them; in fact, `__all__` controls what `from mypackage import *` exports, and here it correctly lists both functions. Option D is wrong because the imports in `__init__.py` use absolute imports (`from mypackage.module1 import func1`), which are not relative and do not depend on the current working directory; relative imports would use a leading dot (e.g., `from .module1 import func1`).

22
Multi-Selecthard

Which TWO of the following statements about Python's `sys.path` are true?

Select 2 answers
A.The current working directory is always the first element in `sys.path`.
B.Module search stops at the first matching directory in `sys.path`.
C.`sys.path` is initialized from the PYTHONPATH environment variable.
D.`sys.path` is a tuple of strings.
E.The directory containing the script being run is added to the beginning of `sys.path` at startup.
AnswersB, E

This is true: the import system walks through the directories and zip archives listed in `sys.path` sequentially, and the first entry that contains the requested module (or package) is used; Python does not continue searching later entries for an alternative. This is why the order of `sys.path` is critical—adding a directory to the front can shadow a standard-library module or another installed package. If no matching module is found, an `ImportError` is raised after the entire list has been exhausted.

Why this answer

Python's import mechanism iterates through `sys.path` in order and stops at the first directory containing the requested module. Option E is correct: the directory containing the script (or the current directory when running interactively) is inserted at the beginning of `sys.path` at startup. Options A, C, and D are false: the current working directory is not always first (the script's directory takes precedence), `sys.path` is initialized from the `PYTHONPATH` environment variable *in addition to* default paths, and `sys.path` is a list, not a tuple.

Therefore, only two statements are true.

Exam trap

The Python Institute often tests that `sys.path` is a list, not a tuple, and that the script's directory, not the current working directory, is inserted first. Candidates may mistakenly think `PYTHONPATH` is the sole source of `sys.path` initialization, but it is only one of several sources.

23
MCQhard

A Python package 'mypackage' contains the following hierarchy: mypackage/ __init__.py subpackage1/ __init__.py module_a.py subpackage2/ __init__.py module_b.py From a script outside the package, a programmer writes: import mypackage.subpackage1.module_a Which statement is true about the import?

A.Only mypackage/__init__.py is executed.
B.No __init__.py files are executed because the import uses a dotted path.
C.After the import, 'mypackage' is not available as a name in the namespace.
D.Both mypackage/__init__.py and mypackage/subpackage1/__init__.py are executed.
AnswerD

When importing `mypackage.subpackage1`, Python executes the `__init__.py` of each package along the dotted path to initialize them as proper packages. This happens because the import system processes each component sequentially: first `mypackage` is imported, which runs its `__init__.py`, then its submodule `subpackage1` is imported, which runs its own `__init__.py`. This two-step initialization is fundamental to Python's package system, ensuring parent packages are fully loaded before their subpackages.

Why this answer

When Python encounters an import statement with a dotted path like `import mypackage.subpackage1.module_a`, it executes the `__init__.py` files for each package in the path in order: first `mypackage/__init__.py`, then `mypackage/subpackage1/__init__.py`. This is because Python must initialize each package before it can access its subpackages or modules. Option D correctly states that both `__init__.py` files are executed.

Exam trap

Python Institute often tests the misconception that dotted imports skip `__init__.py` execution or that only the final module is loaded, when in fact Python executes every `__init__.py` along the dotted path to ensure proper package initialization.

How to eliminate wrong answers

Option A is wrong because Python does not stop at the top-level package; it must also execute `subpackage1/__init__.py` to initialize that subpackage before importing `module_a`. Option B is wrong because `__init__.py` files are always executed when their corresponding package is imported, regardless of whether the import uses a dotted path or a direct package name. Option C is wrong because after `import mypackage.subpackage1.module_a`, the name `mypackage` is bound in the namespace as a reference to the top-level package object, allowing access via `mypackage.subpackage1.module_a`.

24
MCQeasy

Which of the following is a valid way to import a module named 'math' and assign it an alias 'm'?

A.alias math as m
B.from math import * as m
C.import m from math
D.import math as m
AnswerD

`import math as m` is the correct and idiomatic way to import the `math` module while binding it to the local name `m`. The `as` clause in an import statement creates an alias for the module object, so every subsequent reference to `m` (such as `m.sqrt(2)`) accesses the `math` module's functionality without needing to type the full module name. This is a standard feature of the import system, commonly used to shorten long module names or avoid name conflicts.

Why this answer

Python's `import` statement allows you to import a module and assign it an alias using the `as` keyword, as in `import math as m`. This creates a reference to the `math` module under the name `m`, so you can call functions like `m.sqrt(16)` without polluting the namespace with the original module name.

Exam trap

Python Institute often tests the misconception that `alias` is a Python keyword or that `from ... import *` can be combined with `as`, leading candidates to pick options A or B instead of the correct `import ... as ...` syntax.

How to eliminate wrong answers

Option A is wrong because `alias` is not a valid Python keyword; the correct syntax uses `import ... as ...`, not `alias`. Option B is wrong because `from math import *` imports all names from the module into the current namespace, and the `as m` clause is not allowed with the `from ... import *` form; aliasing is only supported with a single imported name or module. Option C is wrong because the syntax `import m from math` is invalid; Python requires the module name to come immediately after `import`, and the alias (if any) must follow the `as` keyword.

25
MCQmedium

A Python script placed in /opt/myapp/script.py fails with ImportError when run from a cron job with the command: python /opt/myapp/script.py. The script works when run manually from the /opt/myapp/ directory. The script contains the line: from . import config. The config module is located in /opt/myapp/lib/config.py with an __init__.py in /opt/myapp/lib/. What is the most likely cause of the failure?

A.The __init__.py file in the lib directory is empty and should contain imports.
B.The lib directory is not in sys.path when the script is run from cron.
C.Relative imports are not allowed in a script that is executed directly because its __name__ is not set to a package name.
D.The cron job uses a different Python interpreter that does not have the required standard library.
AnswerC

When a script is run directly, it is treated as __main__, not as part of a package, so relative imports fail.

Why this answer

When a Python script is executed directly (e.g., `python /opt/myapp/script.py`), its `__name__` is set to `'__main__'`, not to a package name. Relative imports (like `from . import config`) require the importing module to be part of a package with a proper `__name__` reflecting the package hierarchy. Since the script is run as the top-level entry point, the relative import fails with an `ImportError`.

This explains why the script works when run manually from `/opt/myapp/` (if the working directory is set appropriately, but the relative import still fails unless the script is run as a module with `-m`), but fails from cron where the working directory is typically the user's home directory.

Exam trap

Python Institute often tests the distinction between running a script directly (`python script.py`) versus running it as a module (`python -m package.script`), and the trap here is that candidates mistakenly blame `sys.path` or `__init__.py` contents instead of recognizing that relative imports are fundamentally incompatible with direct script execution.

How to eliminate wrong answers

Option A is wrong because an empty `__init__.py` is sufficient to mark a directory as a Python package; it does not need to contain imports. The error is not caused by the contents of `__init__.py`. Option B is wrong because the `lib` directory is not directly in `sys.path`; however, the relative import `from . import config` does not rely on `sys.path` — it relies on the package structure and the `__name__` of the script.

The script's failure is not due to missing `sys.path` entries, but due to the prohibition of relative imports in a directly executed script. Option D is wrong because the cron job uses the same Python interpreter as the manual run (both invoke `python`), and the error is an `ImportError` specific to relative imports, not a missing standard library module.

26
MCQhard

Given package structure: pack/__init__.py, pack/subpack/__init__.py, pack/subpack/mod.py. Inside pack/__init__.py, which import statement correctly imports mod.py using a relative import?

A.from . import subpack.mod
B.from subpack import mod
C.from ..subpack import mod
D.from .subpack import mod
AnswerD

The leading dot indicates a relative import from the current package (`pack`). This statement imports the `mod` submodule from the `subpack` subpackage that is a child of the current package. This is the standard way to import a module from a sibling subpackage in a package, ensuring the import is resolved relative to the current package's location, not the top-level `sys.path`.

Why this answer

`from .subpack import mod` uses a leading dot to indicate a relative import from the current package (`pack`), then navigates into `subpack` and imports `mod`. This is the proper syntax for importing a module from a subpackage within the same parent package.

Exam trap

Python Institute often tests the distinction between absolute and relative imports, and the trap here is that candidates mistakenly use an absolute import (Option B) or incorrect dot syntax (Option A or C) because they confuse the number of dots or the placement of the module name in the import statement.

How to eliminate wrong answers

Option A is wrong because `from . import subpack.mod` is invalid syntax; relative imports require the dot to be followed directly by a package or module name, not a dotted path after the import keyword. Option B is wrong because `from subpack import mod` is an absolute import, which would look for a top-level package named `subpack`, not the one inside `pack`. Option C is wrong because `from ..subpack import mod` uses two dots, which would go up one level from `pack` to its parent, not down into `subpack`.

27
Drag & Dropmedium

Drag and drop the steps to perform unit testing with the unittest framework 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
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

Unit testing with unittest requires importing, creating a TestCase subclass, writing test methods, and calling unittest.main().

28
MCQhard

A package 'pkg' is installed as an egg-link in development mode. Inside the package, there is a module 'submod.py' that uses relative imports. When a developer modifies 'submod.py', they find that changes are not always reflected on import. What is the most likely reason?

A.The sys.path is altered by the egg-link, causing a different module to be loaded.
B.Relative imports are cached in the __init__.py file.
C.Python's module caching in sys.modules prevents re-loading the modified source.
D.The __pycache__ directory is not cleared automatically.
AnswerC

When a module is first imported, Python stores the resulting module object in `sys.modules` under its full qualified name; every later `import` statement checks `sys.modules` first and returns that same object without re-reading the source file. In an egg-link development environment, the source directory is the one being imported, so you are editing the exact file that was loaded — but the interpreter has already cached the compiled, executed version of that module. You must use `importlib.reload(module)` or restart the process to force reparsing and re-execution of the modified `.py` file.

Why this answer

Python caches imported modules in `sys.modules`. When a module is imported, Python stores the module object in `sys.modules` and subsequent imports retrieve it from this cache without re-executing the module's code. Modifying the source file of `submod.py` does not automatically invalidate this cache, so the changes are not reflected unless the module is explicitly reloaded (e.g., with `importlib.reload()`) or the interpreter is restarted.

Exam trap

Python Institute often tests the distinction between source file modification and module caching, where candidates mistakenly think the issue is with bytecode caching (`__pycache__`) or path resolution, rather than the `sys.modules` cache that prevents re-execution of the module's code.

How to eliminate wrong answers

Option A is wrong because an egg-link installs a development mode package by adding a path to `sys.path` that points to the source directory; it does not cause a different module to be loaded—the same source file is used, but the caching issue still applies. Option B is wrong because relative imports are not cached in `__init__.py`; they are resolved at import time based on the package's `__name__` and `__path__`, and caching occurs in `sys.modules`, not in `__init__.py`. Option D is wrong because `__pycache__` stores bytecode files (`.pyc`) for performance, but Python checks the modification time of the source file against the cached bytecode; if the source is newer, it recompiles—so the issue is not about clearing `__pycache__` but about the module object already being in `sys.modules`.

29
MCQmedium

A developer installs a third-party package using pip, but when they try to import it in their script, Python raises a ModuleNotFoundError. The package is definitely installed (pip list shows it). What is the most likely cause?

A.The Python interpreter being used is different from the one where the package was installed.
B.The package name contains a hyphen.
C.The script is in a directory that shadows the package name.
D.The package does not have an __init__.py file.
AnswerA

Pip installs packages into the site-packages directory of the specific Python interpreter that invoked it, e.g., when using `python -m pip` versus a different interpreter. If the script runs under another interpreter—such as a different virtual environment, a system Python, or an IDE's bundled runtime—that interpreter's `sys.path` won't include the package's location, producing an ImportError. This is the classic environment-mismatch cause.

Why this answer

When a package is installed via pip, it is placed into the site-packages directory of a specific Python interpreter. If the developer runs their script with a different Python interpreter (e.g., one from a virtual environment, a different version, or a system Python vs. a user-installed Python), that interpreter's import system will not search the site-packages where the package was installed, resulting in a ModuleNotFoundError even though pip list shows the package. This is the most common cause of such a mismatch.

Exam trap

Python Institute often tests the misconception that a package name with a hyphen is invalid for import, leading candidates to choose option B, but the real issue is interpreter mismatch, which is the most common and subtle cause of ModuleNotFoundError in multi-interpreter environments.

How to eliminate wrong answers

Option B is wrong because Python's import system automatically converts hyphens in package names to underscores (e.g., pip install my-package allows import my_package), so a hyphen in the package name does not cause a ModuleNotFoundError. Option C is wrong because a script shadowing a package name would cause an ImportError or unexpected behavior only if the script's directory contains a module or package with the same name as the imported package, but it would not produce a ModuleNotFoundError; the error would be a different one (e.g., AttributeError or incorrect import). Option D is wrong because __init__.py is only required for regular packages in Python 3.3+ for namespace packages or for packages that need initialization code; third-party packages installed via pip are typically regular packages or namespace packages that work without __init__.py, and its absence does not cause a ModuleNotFoundError.

30
MCQhard

A developer runs 'pip install mypackage' but gets a 'PermissionError'. Which command should be used to install the package for the current user only?

A.sudo pip install mypackage
B.pip install --user mypackage
C.pip install --ignore-installed mypackage
D.pip install --target mypackage
AnswerB

This is correct because the --user flag makes pip install the package into the current user's private site-packages directory (e.g., ~/.local/lib/python3.x/site-packages), which is owned by that user and therefore requires no elevated permissions. It resolves the permission error without altering system Python packages, and the directory is automatically included in sys.path by default. This is a safe, supported way to install packages when you lack administrative rights, though virtual environments are often preferred for isolation.

Why this answer

The `--user` flag instructs pip to install the package into the user's site-packages directory (e.g., `~/.local/lib/pythonX.Y/site-packages` on Unix), which does not require elevated permissions. This avoids the `PermissionError` that occurs when pip tries to write to the system-wide site-packages directory (e.g., `/usr/lib/python3/dist-packages`) without administrator privileges.

Exam trap

Python Institute often tests the misconception that `sudo` is the correct way to fix permission errors in pip, but the exam expects candidates to know the safer, user-scoped `--user` flag as the proper solution for installing packages without administrative rights.

How to eliminate wrong answers

Option A is wrong because `sudo pip install mypackage` runs pip with superuser privileges, which bypasses the permission error but is strongly discouraged as it can corrupt the system Python environment and bypass security checks. Option C is wrong because `--ignore-installed` tells pip to ignore already installed packages and reinstall, but it does not change the installation target directory, so the permission error would still occur. Option D is wrong because `--target mypackage` specifies a custom installation directory (e.g., `./mypackage`) but does not resolve the underlying permission issue; it would still fail if the target directory is not writable or is misused as a package name.

31
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

When mypackage is a single-file module, it contains no namespace for submodules, so `from mypackage import mymodule` treats mymodule as an attribute that must exist in that file. Since no such attribute is defined, the import machinery raises `ImportError: cannot import name 'mymodule' from 'mypackage'` with the file location of the module. This is the most likely cause because the traceback location is the mypackage module itself, not a package directory, and it aligns with how Python distinguishes modules from packages.

Why this answer

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.

32
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

The leading double dot in from ..utils import helpers marks this as a relative import that climbs one level above the current package. If this line appears in main.py at the project root, main.py is being executed as the __main__ module rather than as an importable package member, so its __package__ is empty and there is no parent package to resolve the dots. This raises ImportError: attempted relative import with no known parent package, which is exactly why this is the only statement that fails and the correct answer.

Why this answer

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.

33
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

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.

34
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.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.
AnswerC

Using a virtual environment creates an isolated environment, ensuring your local package is used without affecting or being affected by the global package. This is the standard and most reliable approach.

Why this answer

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 the PCAP exam 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.

35
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

Importing `validate_transaction` directly from its defining submodule and binding it in `finance/__init__.py` creates a single, callable attribute `finance.validate_transaction`. This is the recommended re-export pattern for exposing a clean public API: users get a flat namespace while the implementation remains organized under submodules. The function's original module is unchanged, but the package-level binding gives the desired shortcut.

Why this answer

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.

36
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 Python executes a script from standard input (for example, via `python < script.py`), there is no script directory to place at the front of `sys.path`. In that situation, CPython sets `sys.path[0]` to the empty string `''`, which the import system interprets as "search the current working directory." Because `print(sys.path[0])` prints that empty string, the output is a blank line, and the value itself is the documented signal that the script came from stdin. This is a deliberate design decision so that modules in the current directory remain importable even when no script file path exists.

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.

37
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

`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.

38
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 the desired functions directly into `__init__.py` with relative imports, e.g. `from .submodule import func1`, binds those names in the package's namespace at import time. This is the canonical re-export pattern: after this line, `import package; package.func1` and `from package import func1` both succeed, while the submodule remains accessible as `package.submodule`. It gives the package a stable public API without duplicating logic.

Why this answer

`__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.

39
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

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.

40
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

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.

41
Multi-Selectmedium

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

Select 1 answer
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

Correct syntax: `import math as m` imports the full math module with alias m.

Why this answer

Only B. Option B uses the correct syntax `import math as m` to import the entire math module with alias m. Option A is invalid because the asterisk (*) cannot be combined with an alias in a `from ... import` statement.

Option C is missing the `as` keyword. Option D uses `alias` which is not a valid keyword; the correct keyword is `as`. Option E imports a specific function (sin) from math, not the module itself; therefore it does not satisfy the requirement to import the module and give it an alias.

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.

42
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

PEP 420 introduced implicit namespace packages, which allow a dotted package name to be composed from multiple separate directories on sys.path without requiring __init__.py in any of them. When the import system encounters a directory named home that has no __init__.py, it records that directory as one portion of the package and continues scanning later sys.path entries for additional home directories, assigning the combined list of portions to __path__. This is exactly the mechanism that lets two physically separate directory trees collectively provide the submodules of the package home.

Why this answer

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.

43
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

Python's import machinery validates cached bytecode by comparing the source file's modification time (and often size) with the values stored in the .pyc header. If an installer copies only the .py files without updating their mtimes—for example, by preserving timestamps from the build or using a tool that does not touch the destination files—the old .pyc still appears to match the unchanged source timestamp. Python then loads the stale bytecode instead of recompiling, so even though the .py file on disk contains the new code, the interpreter executes the previous version.

Why this answer

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).

44
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

Setting __all__ = ['Circle', 'Square'] at the top level of shapes.py explicitly whitelists those two classes for wildcard imports; any other public name, such as Triangle, will be ignored by from shapes import *. This is the canonical Python mechanism for declaring a module's public API, and it is also honored by documentation generators and linters, making the module's intended exports unambiguous.

Why this answer

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.

45
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

This is the canonical Python idiom used to determine whether the current file is being run as the top-level script. When the interpreter executes a script directly, it sets the global variable __name__ to the string '__main__'; when the file is imported as a module, __name__ is set to the module's import name instead. The if block therefore only runs for standalone execution, which is exactly what the script intends. This guard also supports running with python -m, where __name__ is also '__main__'.

Why this answer

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.

46
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

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.

47
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

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.

Ready to test yourself?

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