Courseiva

CCNA Modules and Packages Questions

10 of 85 questions · Page 2/2 · Modules and Packages · Answers revealed

76
MCQhard

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

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

This is the correct diagnosis because the Python error 'AttributeError: module 'mypkg.submod1' has no attribute 'func'' means the module was successfully loaded, but the requested attribute 'func' is simply not present at the module's top level. This can happen if the function was never defined, is misspelled, or was removed. Attribute lookup on a module object checks its namespace, and a missing key raises AttributeError — not ImportError. The fix is to define func in submod1 (or import it there) before calling it.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

77
Multi-Selectmedium

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

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

Defining `__all__` in __init__.py is the canonical way to specify which names are exported when `from package import *` is used, effectively controlling the package's public API. Only the names listed in `__all__` (and not explicitly excluded) are bound in the importing namespace, allowing explicit control over what users can access via star imports.

Why this answer

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

Exam trap

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

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

79
Multi-Selecthard

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

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

When a module is first imported, its top-level code runs, and the resulting module object is stored in the sys.modules dictionary. Subsequent import statements for the same module retrieve that cached object and bind it to the requested name, skipping re-execution of the module body. This ensures that expensive initializations and side effects (such as establishing database connections) happen exactly once per process.

Why this answer

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

Exam trap

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

80
MCQeasy

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

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

This is the correct approach because it explicitly imports only the sqrt function from the math module into the current namespace. After execution, you can call sqrt(9) directly without a module prefix, which improves readability and reduces the chance of name collisions. It is a targeted, efficient way to bring in only the specific functionality you need.

Why this answer

`from math import sqrt` binds only the `sqrt` function into the current namespace, avoiding name collisions with other math functions. While the `math` module itself is still fully loaded, this form avoids introducing extra global names and provides direct access to `sqrt`, which is more convenient and slightly faster than attribute lookup with `math.sqrt`. It is the most appropriate when only that one function is needed.

Exam trap

Python Institute often tests the misconception that `import module.function` (e.g., `import math.sqrt`) is valid. Python allows `import package.submodule` only when the target is a submodule, but `sqrt` is a function, not a submodule. For functions, use `from module import function` or `import module` and then `module.function`.

How to eliminate wrong answers

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

81
MCQmedium

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

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

Two leading dots in a relative import ascend one level in the package hierarchy: from a module inside `sub_package`, `..` refers to `my_package`. Therefore `from ..module_a import foo` asks Python to locate `module_a` as a sibling of `sub_package` within that parent package, which exactly matches the described structure. This is the correct way to import `foo` without relying on an absolute top-level path.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

82
Multi-Selectmedium

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

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

Relative imports are not intrinsically tied to the filesystem path of the file; they are only valid when the interpreter has assigned the importing module a non-empty `__package__` attribute, which happens only when that module is imported as part of a package (e.g., `import pkg.subpkg.mod2`). If you run a module directly, Python sets `__package__` to `None`, so a statement like `from . import sibling` fails with "attempted relative import with no known parent package" because there is no package context to anchor the leading dot.

Why this answer

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

Exam trap

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

83
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

Circular imports arise when two modules mutually reference each other at import time, so Python cannot fully initialise either. Extracting shared logic into a third module breaks the cycle, satisfying the stem's requirement to resolve the ImportError through restructuring rather than deferred imports or runtime workarounds.

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.

84
Multi-Selecthard

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

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

The from-import statement directly fetches the 'calculate' attribute from the 'app.operations.math_ops' module and binds it in the current namespace. This is the most common and concise way to bring a function into scope, and it bypasses the need to reference the module path each time. The import system locates the module using the dotted path, then performs attribute lookup for the function.

Why this answer

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

Exam trap

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

85
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

Python treats a directory as a regular package only when it contains an __init__.py file, which executes on import and defines the package namespace. Namespace packages lack this file, so its presence is what distinguishes a regular package from that alternative.

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.

← PreviousPage 2 of 2 · 85 questions total

Ready to test yourself?

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