A module is a .py file; packages are directories with __init__.py (Python 3.3+ namespace packages differ). Use import to reuse code—like ES modules in JavaScript or packages in Java.
Import styles
import math
from datetime import date
import json as js
Prefer explicit imports over from module import *—it pollutes namespaces and hides origins.
__name__ == "__main__"
def main():
print("running as script")
if __name__ == "__main__":
main()
Code under this guard runs only when executed directly, not when imported—essential for reusable modules.
Important interview questions and answers
- Q: import vs from import?
A:import mathrequiresmath.sqrt;from math import sqrtbindssqrtdirectly. - Q: What does __name__ hold when imported?
A: The module's dotted name (e.g.,mypackage.utils), not__main__.
Self-check
- What guard runs code only as a script?
- Why avoid
import *?
Tip: Prefer explicit imports—import json beats from json import * for readable codebases.
Interview prep
- import vs from import?
import mathneedsmath.sqrt;from math import sqrtbindssqrtdirectly.- __name__ when imported?
Module dotted path—not
__main__—so guarded code does not run on import.