0
0
Pythonprogramming~5 mins

__init__ file role in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the __init__.py file in a Python package?
The __init__.py file tells Python that the directory should be treated as a package. It can also initialize package-level variables or import submodules.
Click to reveal answer
beginner
True or False: Without an __init__.py file, Python cannot recognize a folder as a package.
False. Since Python 3.3+, folders without __init__.py can be treated as namespace packages.
Click to reveal answer
intermediate
Can __init__.py contain executable code? What is a common use for this?
Yes, __init__.py can contain executable code. A common use is to initialize package variables or import specific classes/functions to simplify access.
Click to reveal answer
beginner
What happens if __init__.py is empty?
If __init__.py is empty, the folder is still recognized as a package, but no initialization code runs.
Click to reveal answer
intermediate
How does __init__.py help with importing submodules in a package?
By importing submodules inside __init__.py, you can make them available directly when importing the package, making code cleaner and easier to use.
Click to reveal answer
What does the __init__.py file do in a Python folder?
ACompiles Python code
BRuns the main program
CDeletes the folder contents
DMarks the folder as a Python package
Can __init__.py contain code that runs when the package is imported?
ANo, it must be empty
BYes, it can contain initialization code
COnly comments are allowed
DIt only contains variable declarations
If __init__.py is missing, what happens when you try to import the folder as a package?
APython ignores the folder
BPython raises an ImportError
CPython treats it as a package anyway
DPython converts it to a module
How can __init__.py simplify importing submodules?
ABy importing submodules inside __init__.py
BBy compiling submodules
CBy renaming submodules
DBy deleting submodules automatically
Is it mandatory to have __init__.py in Python 3.12+ packages?
ANo, but recommended for explicit packages
BNo, it is deprecated
CYes, always mandatory
DOnly for Python 2
Explain the role of the __init__.py file in a Python package.
Think about how Python knows a folder is a package.
You got /4 concepts.
    Describe how __init__.py can be used to simplify imports in a package.
    Consider how you want to access parts of a package easily.
    You got /3 concepts.