Python Modules & Packages MCQs

1 min read

Python modules are single files containing Python code (functions, classes, and variables) that can be imported and reused across different scripts, while packages are directories containing multiple modules structured in a hierarchical namespace. The Python import system utilizes built-in directories, third-party libraries, and search paths (sys.path) to locate and load modules efficiently. Understanding how to organize code into modules and packages prevents naming conflicts, enhances code modularity, and is a core requirement for building scalable software applications.

1. What is a module in Python?

0) A file containing Python definitions and statements
1) A built-in database management tool
2) A folder containing sub-packages
3) A function used to compile Python source code
Correct Answer:

2. Which file extension is typically used for Python module files?

0) .pt
1) .py
2) .pym
3) .module
Correct Answer:

3. Which keyword is used to load a module into a Python script?

0) include
1) require
2) import
3) using
Correct Answer:

4. How can you import a specific function `sqrt` from the `math` module?

0) import sqrt from math
1) from math import sqrt
2) get sqrt from math
3) include math.sqrt
Correct Answer:

5. How can you give an imported module an alias named `m`?

0) import math as m
1) import math to m
2) import math rename m
3) alias import math as m
Correct Answer:

6. What does the `__name__` variable hold when a Python script is run directly?

0) __main__
1) __module__
2) __file__
3) __direct__
Correct Answer:

7. What does `__name__` hold when a module is imported into another script?

0) __main__
1) The name of the module itself
2) None
3) True
Correct Answer:

8. Which dictionary stores all currently imported modules in Python?

0) sys.path
1) sys.modules
2) os.modules
3) builtins.__dict__
Correct Answer:

9. Which list defines the directory search path for Python modules?

0) sys.path
1) sys.env
2) os.path
3) sys.dirs
Correct Answer:

10. Can a Python package contain other packages?

0) No, packages can only contain modules
1) Yes, they can contain sub-packages and sub-modules
2) Only if configured via an external compiler
3) Yes, but only up to two levels deep
Correct Answer:

11. What is the purpose of the `__all__` variable in a module?

0) To list all variables that should be ignored
1) To specify a list of public names exported when `from module import *` is used
2) To import all external third-party dependencies
3) To handle global exception logging
Correct Answer:

12. Is `__init__.py` mandatory for a directory to be recognized as a package in Python 3.3 and newer?

0) Yes, strictly required always
1) No, Python 3 supports implicit namespace packages without `__init__.py`
2) Only on Windows operating systems
3) Only if you use relative imports
Correct Answer:

13. What is an implicit namespace package?

0) A package created without an `__init__.py` file spanning multiple directories
1) A hidden package built into the C standard library
2) A package that cannot be imported
3) A module that automatically deletes itself after execution
Correct Answer:

14. Which symbol is used for a relative import referencing the current package/directory?

0) .
1) ..
2) ~
3) /
Correct Answer:

15. Which symbol is used for a relative import referencing the parent package?

0) .
1) ..
2) ...
3) //
Correct Answer:

16. What kind of import error occurs when a module cannot be found?

0) ModuleNotFoundError
1) PackageNotFoundError
2) ImportNotFoundException
3) LookupError
Correct Answer:

17. What is a built-in module in Python?

0) A module written in C and compiled directly into the Python interpreter
1) A module downloaded from PyPI using pip
2) A user-defined script saved in the current directory
3) A file generated automatically by text editors
Correct Answer:

18. Which function can be used to reload a previously imported module dynamically?

0) importlib.reload()
1) sys.reload()
2) os.reload_module()
3) reload()
Correct Answer:

19. Which built-in module provides functions to manipulate file paths and directory structures?

0) os.path
1) sys.path
2) math
3) itertools
Correct Answer:

20. What is the modern object-oriented filesystem path library introduced in Python 3.4?

0) pathlib
1) oslib
2) filetree
3) dirpath
Correct Answer:

21. Can you import a module whose name starts with a number?

0) Yes, using standard import syntax
1) No, because module names must follow valid Python identifier rules
2) Yes, if enclosed in backticks
3) Only via `importlib` dynamic loading
Correct Answer:

22. How do you dynamically load a module by its string name?

0) importlib.import_module()
1) sys.load()
2) load_module()
3) eval_import()
Correct Answer:

23. Where does Python look first when an import statement is executed?

0) The current working directory
1) Built-in modules
2) Site-packages directory
3) Environment variables
Correct Answer:

24. What happens if a module defines code at the top level (outside any functions or classes) when imported?

0) It is ignored
1) It is executed once upon import
2) It triggers a SyntaxError
3) It only executes when a function is called
Correct Answer:

25. What is the purpose of the `PYTHONPATH` environment variable?

0) To specify additional directories where Python should look for modules and packages
1) To set the default password for pip installations
2) To define the installation path of the Python interpreter executable
3) To store temporary compiled bytecode cache
Correct Answer:

26. What are `.pyc` files?

0) Compressed source code archives
1) Compiled bytecode cache files created by Python
2) Configuration files for package managers
3) C++ extension files linked to Python
Correct Answer:

27. In which folder are `.pyc` bytecode cache files typically stored in modern Python versions?

0) __pycache__
1) __cache__
2) .bytecode
3) bin
Correct Answer:

28. How can you suppress the creation of `__pycache__` directories during imports?

0) Set the `PYTHONDONTWRITEBYTECODE` environment variable to a non-empty value
1) Use the `-no-cache` flag with the python command
2) Delete the `__init__.py` file
3) Pass `nocache=True` inside the import statement
Correct Answer:

29. What is a circular import in Python?

0) When two or more modules depend on and try to import each other directly or indirectly
1) When a module imports itself recursively 1000 times
2) An import statement written inside a `for` loop
3) Importing modules in alphabetical order
Correct Answer:

30. What exception is commonly raised at runtime due to circular imports when names are not yet bound?

0) AttributeError or ImportError
1) CircularDependencyError
2) MemoryError
3) TypeError
Correct Answer:

31. How can circular imports often be resolved?

0) By placing imports inside functions or methods where they are needed rather than at the top level
1) By renaming all files to start with numbers
2) By deleting the `sys.modules` dictionary
3) By disabling bytecode compilation
Correct Answer:

32. What is the recommended style for multiple imports according to PEP 8?

0) Import each module on a separate line
1) Import all modules on a single line separated by semicolons
2) Group all imports inside a giant try-except block
3) Alphabetize them with no regard for line count
Correct Answer:

33. According to PEP 8, in what order should import statements be grouped?

0) Standard library imports, related third-party imports, local application/library specific imports
1) Third-party imports first, then standard library, then local
2) Random order based on file creation date
3) Local imports first, then standard library, then third-party
Correct Answer:

34. What is a namespace package without physical subdirectories called?

0) An implicit namespace package
1) A virtual package
2) A compiled static package
3) A stub package
Correct Answer:

35. What is the function of the `dir()` function when called without arguments on a module?

0) Returns a list of names defined in the current module's symbol table
1) Returns the absolute path of the directory containing the script
2) Deletes all local variables
3) Lists all installed packages on the machine
Correct Answer:

36. What does `dir(module_name)` return?

0) A sorted list of attributes and methods available in that module
1) The directory path where the module is saved
2) The size of the module file in bytes
3) The list of users who imported the module
Correct Answer:

37. Can a Python script be executed as a module using the command line?

0) Yes, using `python -m module_name`
1) No, scripts can only be executed directly by filename
2) Only if compiled to an executable binary
3) Only on Linux environments
Correct Answer:

38. What happens when you run `python -m mymodule`?

0) Python searches `sys.path` for `mymodule`, executes it as `__main__`, and runs it
1) Python deletes `mymodule` from the disk
2) Python converts `mymodule` into a package
3) Python runs unit tests inside the module
Correct Answer:

39. Which built-in module attribute gives the absolute file path of the module?

0) __file__
1) __path__
2) __dir__
3) __source__
Correct Answer:

40. What attribute does a package module possess that regular modules do not?

0) __path__
1) __package__
2) __children__
3) __submodules__
Correct Answer:

41. What does the `__path__` attribute of a package contain?

0) A list containing the absolute path(s) of the package's directory
1) The path of the Python interpreter
2) A string pointing to the parent script
3) The installation path of pip
Correct Answer:

42. What is a stub file used in Python typing (`.pyi`)?

0) A file containing type annotations for modules without executing the actual code implementation
1) An incomplete script template generated by IDEs
2) A backup file created during compilation errors
3) A configuration file for testing frameworks
Correct Answer:

43. How does Python handle package initialization in Python 3 compared to older practices?

0) `__init__.py` is optional for packages, though still used for initialization code and defining `__all__`
1) `__init__.py` is completely deprecated and causes syntax errors
2) `__init__.py` must be written in C language
3) Packages cannot contain any initialization code whatsoever
Correct Answer:

44. What is the effect of `from module import *`?

0) Imports all names from the module except those starting with an underscore (_)
1) Imports every single variable including private ones
2) Imports only the module name itself
3) Raises an error unless `__all__` is absent
Correct Answer:

45. Why is `from module import *` generally discouraged in production code?

0) It clutters the local namespace and makes it unclear which names are present or where they came from
1) It crashes the Python interpreter due to memory overload
2) It prevents bytecode caching
3) It is illegal under Python license terms
Correct Answer:

46. What is an egg or wheel (`.whl`) file in Python packaging?

0) A built-package format used for distributing Python software and libraries
1) A raw text script format for web browsers
2) A database backup file for modules
3) An encrypted configuration file for virtual environments
Correct Answer:

47. Which tool is standard for installing packages from PyPI?

0) pip
1) conda
2) easy_install
3) npm
Correct Answer:

48. What command lists all packages currently installed in the active Python environment using pip?

0) pip list
1) pip show
2) pip search
3) pip find
Correct Answer:

49. What is a virtual environment in Python?

0) An isolated environment that allows you to manage dependencies for a specific project without conflicts
1) A cloud-based Python IDE running in a web browser
2) An emulator for running Python on non-standard operating systems
3) A sandbox that prevents Python from accessing the hard drive
Correct Answer:

50. Which built-in module is used to create virtual environments?

0) venv
1) virtualenv
2) envbuilder
3) pyenv
Correct Answer:

51. What command creates a virtual environment named `.venv` using the built-in module?

0) python -m venv .venv
1) python create-env .venv
2) venv init .venv
3) pip install venv .venv
Correct Answer:

52. What is the standard name of the metadata configuration file used in modern Python packaging (replacing older setup.py scripts)?

0) pyproject.toml
1) package.json
2) config.yaml
3) setup.toml
Correct Answer:

53. What happens if you try to import a module that exists both as a built-in module and as a local file with the same name in the current directory?

0) The built-in module takes precedence
1) The local file takes precedence
2) Python raises a NameCollisionError
3) Both modules are merged automatically
Correct Answer:

54. Can a module name contain hyphens (e.g., `my-module.py`)?

0) Yes, and it can be imported normally using `import my-module`
1) No, because a hyphen is interpreted as a subtraction operator in Python identifiers
2) Only if enclosed in quotes
3) Yes, via `importlib` only
Correct Answer:

55. How can you load a module whose filename contains a hyphen (e.g., `my-module.py`)?

0) Using `importlib.machinery` and `importlib.util` dynamic loading APIs
1) By replacing hyphens with underscores automatically
2) It is completely impossible in Python
3) By renaming it via the import statement
Correct Answer:

56. What is the function of the `__loader__` attribute in a module?

0) It references the loader object used to load the module
1) It stores the memory address of the module loader thread
2) It contains a boolean flag indicating if loading was successful
3) It lists all sub-loaders
Correct Answer:

57. What is a meta-path finder in Python's import system?

0) An object that implements `find_spec()` to locate modules during imports
1) A script that maps out package hierarchies visually
2) An algorithm that optimizes search path order
3) A debugger tool for tracking module load times
Correct Answer:

58. Where are meta-path finders registered?

0) sys.meta_path
1) sys.path
2) sys.modules
3) os.environ
Correct Answer:

59. What is a module spec (`ModuleSpec`)?

0) An object containing the import-related information (like name, loader, origin) for a module
1) A specification document for writing PEP-compliant code
2) A requirements file for pip
3) A blueprint for class inheritance
Correct Answer:

60. Which function is used to create a module spec programmatically?

0) importlib.util.spec_from_loader()
1) sys.create_spec()
2) importlib.new_spec()
3) module.spec()
Correct Answer:

61. How do you execute a newly created module object from a spec?

0) importlib.util.module_from_spec() followed by loader.exec_module()
1) module.execute()
2) sys.run(spec)
3) exec(spec)
Correct Answer:

62. What is a namespace package useful for?

0) Splitting a single Python package across multiple directories or separate distributions
1) Creating hidden modules that cannot be inspected
2) Speeding up execution by bypassing bytecode compilation
3) Encrypting source code files
Correct Answer:

63. Can an implicit namespace package contain an `__init__.py` file?

0) No, if it contains an `__init__.py` file, it becomes a regular package instead of a namespace package
1) Yes, it is required for sub-packages
2) Only if placed in the parent directory
3) Yes, but it must be empty
Correct Answer:

64. What does `sys.meta_path` contain by default?

0) Finders for built-in modules, frozen modules, and path-based modules
1) A list of all active virtual environments
2) Paths to user-installed site-packages
3) Environment variables related to Python path
Correct Answer:

65. What are frozen modules in Python?

0) Modules whose compiled bytecode is stored directly inside the Python interpreter binary
1) Modules that are locked and cannot be modified or reloaded
2) Deprecated modules that are no longer supported
3) Modules that require a frozen execution environment
Correct Answer:

66. What error is raised if you perform a relative import outside of any package (e.g., in a top-level script run directly)?

0) ImportError: attempted relative import with no known parent package
1) ValueError: invalid module reference
2) ModuleNotFoundError: parent package missing
3) SyntaxError: relative import not allowed
Correct Answer:

67. How can you programmatically add a new directory to Python's search path at runtime?

0) sys.path.append('/path/to/directory')
1) sys.modules.add('/path/to/directory')
2) os.path.add('/path/to/directory')
3) import.path('/path/to/directory')
Correct Answer:

68. Where in `sys.path` is the directory of the currently running script typically placed?

0) At the very beginning (index 0)
1) At the very end
2) In the middle
3) It is not included in sys.path
Correct Answer:

69. Why is the script's own directory placed at index 0 of `sys.path`?

0) So that local modules take precedence over installed library modules of the same name
1) To speed up interpreter startup time
2) To prevent accidental imports of standard library modules
3) It is a historical bug kept for backward compatibility
Correct Answer:

70. What is a potential danger of having the current working directory at index 0 of `sys.path`?

0) Accidentally shadowing standard library modules if a local file has the same name (e.g., `math.py`)
1) Memory leaks during long-running server processes
2) Inability to import third-party packages
3) Automatic deletion of source files
Correct Answer:

71. What is the role of `site-packages` directory?

0) It is the standard directory where third-party Python packages installed via pip reside
1) It stores website templates for web frameworks
2) It contains configuration files for the Python website
3) It holds local user documentation
Correct Answer:

72. How can you check the version of an installed package programmatically?

0) Using `importlib.metadata.version('package_name')`
1) Checking `package_name.__version__` (if defined)
2) Both of the above methods
3) Using `sys.version(package_name)`
Correct Answer:

73. Which module was introduced in Python 3.8 to access installed package metadata without importing them?

0) importlib.metadata
1) pkg_resources
2) sys.metadata
3) metafinder
Correct Answer:

74. What is `pkg_resources` (part of `setuptools`) historically used for?

0) Managing package discovery, resource access, and entry points, though now largely superseded by `importlib.metadata` and `packaging`
1) Compiling C extensions
2) Managing virtual machine memory
3) Executing unit tests
Correct Answer:

75. What is an entry point in Python packaging?

0) A mechanism for plugins and command-line scripts exposed by installed packages
1) The `main()` function of a script
2) The first line of an `__init__.py` file
3) The URL of the PyPI repository
Correct Answer:

76. How do you define a command-line script entry point in modern `pyproject.toml`?

0) Under `[project.scripts]`
1) Under `[executables]`
2) Under `[bin]`
3) Under `[cli]`
Correct Answer:

77. What is a source distribution (`sdist`) in Python packaging?

0) An archive containing raw source code and setup configuration files, requiring building before installation
1) A pre-compiled binary installer specific to Windows
2) A text file listing all module dependencies
3) A documentation webpage bundle
Correct Answer:

78. What is a wheel (`.whl`) distribution?

0) A built-package format that installs directly without needing a build step on the target machine
1) A circular dependency resolver
2) An automated test runner script
3) A GUI configuration tool for pip
Correct Answer:

79. What tool is commonly used to build sdists and wheels from a `pyproject.toml` configuration?

0) build
1) compile
2) pack
3) make
Correct Answer:

80. What tool is used to upload package distributions to PyPI?

0) twine
1) upload
2) pip-push
3) pypi-uploader
Correct Answer:

81. What is the purpose of a `MANIFEST.in` file in traditional packaging?

0) To specify additional non-Python files (like README, license, data files) to include in a source distribution
1) To list all Python module dependencies
2) To configure logging rules
3) To map out package import paths
Correct Answer:

82. How do you handle package data files in modern Python packaging?

0) Configured via `tool.setuptools.package-data` or similar backend keys in `pyproject.toml`
1) Placed automatically in the root directory
2) They are not supported in Python 3
3) Stored in environment variables
Correct Answer:

83. Which module can be used to access data files stored inside a package in a zip-safe manner (modern approach)?

0) importlib.resources
1) os.files
2) sys.resources
3) pkg_files
Correct Answer:

84. What is a zip-safe package?

0) A package that can be correctly imported and run directly when bundled inside a zip archive
1) A package compressed with a secure password
2) A package that passes antivirus scanning
3) A package that has no external dependencies
Correct Answer:

85. What happens when you import a module located inside a zip file?

0) Python's zip importer extracts/reads the module code directly from the archive without full disk extraction
1) Python raises a ZipImportError
2) The zip file must be manually unzipped before importing
3) The interpreter refuses to run
Correct Answer:

86. Can you define multiple modules inside a single `.py` file?

0) Yes, any number of classes and functions can be defined in one file, forming that single module
1) No, one file can only contain one class or function
2) Only if separated by special comment markers
3) Only in packages with `__init__.py`
Correct Answer:

87. What is a module alias statement syntax?

0) import long_module_name as lmn
1) alias long_module_name as lmn
2) using long_module_name as lmn
3) import as lmn long_module_name
Correct Answer:

88. Is it possible to import a module inside a function block?

0) Yes, local imports are fully valid and executed when the function runs
1) No, all import statements must be at the very top of the file
2) Only if the function is a generator
3) Only if the module is built-in
Correct Answer:

89. What is a common reason to use local/inside-function imports?

0) To avoid circular dependencies or to speed up initial script startup time by deferring heavy imports
1) To make the code run twice as fast globally
2) To bypass PEP 8 style checking entirely
3) Required for all object-oriented programs
Correct Answer:

90. What does `sys.modules.get('module_name')` return if the module has not been imported yet?

0) None
1) KeyError
2) False
3) An empty module object
Correct Answer:

91. How can you check if a module is currently loaded in memory without importing it?

0) By checking if `'module_name' in sys.modules`
1) By using `importlib.is_loaded('module_name')`
2) By checking `os.modules`
3) By catching `ModuleNotFoundError` during an import trial
Correct Answer:

92. What is the effect of deleting a module from `sys.modules` (e.g., `del sys.modules['my_module']`)?

0) Subsequent imports of that module will force Python to reload and re-execute it from scratch
1) The source file on disk is permanently deleted
2) The Python interpreter crashes immediately
3) Nothing happens, sys.modules is read-only
Correct Answer:

93. What is an abstract base class or extension module interface often written in?

0) C, C++, or Rust (using bindings like Pybind11, Cython, or Maturin)
1) HTML and CSS
2) Java bytecode
3) SQL scripts
Correct Answer:

94. What file extension do compiled C extension modules typically have on Linux/Unix systems?

0) .so
1) .pyd
2) .dll
3) .exe
Correct Answer:

95. What file extension do compiled C extension modules typically have on Windows systems?

0) .pyd
1) .so
2) .lib
3) .dll
Correct Answer:

96. Can you inspect the docstring of an imported module?

0) Yes, via `module_name.__doc__`
1) No, docstrings are stripped out during import
2) Only by using the `help()` function
3) Only in debug mode
Correct Answer:

97. Where should a module-level docstring be placed?

0) At the very top of the module file before any code statements
1) At the very bottom of the file
2) Inside the first function definition
3) Inside the `__init__.py` file only
Correct Answer:

98. What is a namespace collision in module imports?

0) When two modules share the same name, causing one to shadow or conflict with another
1) When two threads try to import the same module simultaneously causing a deadlock
2) When a module exceeds its allocated memory limit
3) When a syntax error occurs in a package header
Correct Answer:

99. How does Python protect against multiple threads importing the same module concurrently and causing race conditions?

0) Using an import lock mechanism internal to the interpreter
1) By disabling multi-threading during imports
2) By raising a ThreadSafetyError
3) It does not protect; thread safety is left entirely to the user
Correct Answer:

100. What is the primary benefit of organizing code into modules and packages?

0) Maintainability, reusability, modularity, and namespace organization
1) Automatic code optimization and GPU acceleration
2) Encryption of source code intellectual property
3) Elimination of all runtime bugs
Correct Answer:
← Previous: Python List Comprehension MCQs
Next →: Python Multithreading & Concurrency MCQs
JavaScript Asynchronous Programming MCQs

JavaScript Asynchronous Programming

Asynchronous programming in JavaScript enables non-blocking execution, allowing long-running operations such as network requests, file reading, or timers to run…

By MCQs Generator
JavaScript Variables & Datatypes MCQs

JavaScript Variables & Datatypes MCQs

JavaScript uses variables as named containers to store data values, declared using keywords such as var, let, and const. The…

By MCQs Generator
Python Control Flow MCQs

Python Control Flow MCQs

Control flow statements regulate the order in which individual code statements are evaluated and executed in a Python program. Python…

By MCQs Generator