0
0
Pythonprogramming~20 mins

Package structure and usage in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Package Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of importing a submodule
Consider this package structure:

mypackage/
  __init__.py
  module_a.py
  subpackage/
    __init__.py
    module_b.py

In module_b.py, there is a function def greet(): return 'Hello from B'.

What is the output of this code?

from mypackage.subpackage import module_b
print(module_b.greet())
Python
from mypackage.subpackage import module_b
print(module_b.greet())
AModuleNotFoundError
BAttributeError
CImportError
DHello from B
Attempts:
2 left
💡 Hint
Think about how Python imports functions from submodules inside packages.
Predict Output
intermediate
2:00remaining
Effect of __init__.py on package import
Given this package structure:

mypackage/
  __init__.py
  utils.py

and __init__.py contains:
from .utils import helper

and utils.py contains:
def helper():
    return 'Helping'

What is the output of this code?

import mypackage
print(mypackage.helper())
Python
import mypackage
print(mypackage.helper())
AHelping
BAttributeError
CImportError
DNameError
Attempts:
2 left
💡 Hint
Check what __init__.py exposes when importing the package.
🔧 Debug
advanced
2:00remaining
Why does this import fail?
You have this package structure:

mypackage/
  __init__.py
  tools.py


In tools.py you have:
def tool():
    return 'Tool here'


You run this code from outside the package folder:

from mypackage import tool
print(tool())


But it raises an error. What is the error?
Python
from mypackage import tool
print(tool())
AAttributeError
BImportError
CModuleNotFoundError
DNameError
Attempts:
2 left
💡 Hint
Check what names are exposed by mypackage when importing.
📝 Syntax
advanced
2:00remaining
Correct relative import syntax inside a package
Inside mypackage/subpackage/module_c.py, you want to import func from mypackage/module_a.py.

Which import statement is correct?
Afrom ..module_a import func
Bfrom .module_a import func
Cimport module_a.func
Dfrom mypackage.module_a import func
Attempts:
2 left
💡 Hint
Think about how many levels up you need to go to reach module_a.
🚀 Application
expert
2:00remaining
Number of modules loaded after import
Given this package structure:

mypackage/
  __init__.py
  alpha.py
  beta.py
  gamma/
    __init__.py
    delta.py


Where:
- __init__.py in mypackage imports alpha and gamma
- __init__.py in gamma imports delta

What is the total number of distinct modules loaded into memory after running:

import mypackage
Python
import mypackage
A3
B1
C4
D2
Attempts:
2 left
💡 Hint
Count the modules explicitly imported during the package import.