Learn the correct import directives for accessing module_b within a nested Python package structure. Understand absolute and relative import techniques for efficient code organization.
Table of Contents
Question
With regards to the directory structure below, select the proper forms of the directives in order to import module_b. (Choose two.)
A. import module_b
B. import pypack.upper.module_b
C. from pypack.upper import module_b
D. import upper.module_b
Answer
Based on the directory structure provided in the image, the correct forms of directives to import module_b are:
B. import pypack.upper.module_b
C. from pypack.upper import module_b
Explanation
- Option B: import pypack.upper.module_b
This is an absolute import that specifies the full path from the root package (pypack) to the module. It’s a valid way to import module_b from anywhere in the project. - Option C: from pypack.upper import module_b
This is also an absolute import, but it allows you to use module_b directly without prepending the package names. It’s equally correct and often preferred for cleaner code.
Options A and D are incorrect because:
- Option A (import module_b) would only work if you were in the ‘upper’ directory or had added it to the Python path.
- Option D (import upper.module_b) is incorrect because it doesn’t include the root package name ‘pypack’.
In Python, it’s generally recommended to use absolute imports (like B and C) as they are more explicit and less prone to errors when refactoring code. However, the choice between B and C often depends on how you plan to use the module in your code and personal or project-specific style preferences.
Python Institute PCAP-31-03 certification exam practice question and answer (Q&A) dump with detail explanation and reference available free, helpful to pass the Python Institute PCAP-31-03 exam and earn Python Institute PCAP-31-03 certification.