What are modules and packages, and how does import work?
β‘ Short Answer
A module is a single .py file; a package is a folder of modules (traditionally with __init__.py). `import` runs the module once and caches it in sys.modules, so re-imports are cheap. Use `if __name__ == '__main__':` to separate 'run as script' code from 'imported as a module' code.
βCoffee Chat Question
Concept Made Simple
βWhat are modules and packages, and how does import work?β
π§ Mind Map Answer
Remember It Faster
β¨οΈHands-on Keyboard
Learn by Doing
# mymath.py
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3)) # only when run directly
# other.py
from mymath import add
print(add(10, 5)) # import doesn't run the __main__ block15
π₯What If?
Think Beyond the Expected
What is the point of `if __name__ == '__main__':`?
It lets a file work both as a runnable script and an importable module. When run directly, __name__ is '__main__' and the block executes; when imported, __name__ is the module name, so that block is skipped β preventing your test/CLI code from firing on import.
πReal World
Every project is organized into modules/packages; the `__main__` guard is why importing a utility file doesn't accidentally run its demo code β a detail interviewers check that beginners often miss.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βNaming a file the same as a stdlib module (shadowing)
- βWildcard `from x import *`
- βCreating circular imports
β Best Practices
- βGuard script code with `if __name__ == '__main__'`
- βPrefer explicit imports over `import *`
- βKeep packages cohesive; avoid circular deps
πFollow-up Questions
- 1Absolute vs relative imports?
- 2What causes a circular import and how do you fix it?
- 3How does Python find modules (sys.path)?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Modules (Python) Interview question: "What are modules and packages, and how does import work?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.