ProgrammingPython Developer

Describe the features of namespace and module organization in Python. How does importing work, and how can you avoid name conflicts in a large project?

Pass interviews with Hintsage AI assistant

Answer.

In Python, a namespace is a dictionary that binds names to objects. The levels of namespaces are local, global, and built-in. Modules are separate namespaces for organizing code. When importing, Python creates a new namespace for each module.

How Importing Works

  • import module — imports the module and access objects through module.name.
  • from module import name — imports an object from the module directly into the current namespace (risk of name conflicts).
  • as — allows you to set an alias.

To avoid name conflicts:

  • Use explicit module imports (import mymodule), not asterisks (from... import *).
  • Organize your project with packages (directories with __init__.py).
  • Use unique, descriptive names;
  • Apply aliases (import module as m).

Example Structure

project/
  package/
    __init__.py
    module1.py
    module2.py
import package.module1 from package.module2 import function as fn

Trick Question.

Question: What happens if you import a module twice? Will the entire module's code run again?

Answer: No. During the first import, the module is executed and the result is cached in sys.modules. A repeated import returns the already loaded module object, and its code is not executed again.

# module.py print('Hello!') # main.py import module # prints Hello! import module # prints nothing

Examples of Real Errors Due to Ignorance of the Topic's Nuances.


Story

Developers used from settings import * in several modules, resulting in local variables being unexpectedly "overwritten" when settings were changed, causing hard-to-detect bugs.

Story

In a large project, different teams created modules with the same names (for example, utils.py). During integration, the "identical" named modules "overrode" each other, leading to unexpected behavior and complex bugs.

Story

In one of the libraries, they tried to "hot-reload" the module with new settings using importlib.reload. They did not take into account that already imported other modules retained old references to the objects, causing changes not to be applied throughout the application.