Python / Core Python Fundamentals Interview Questions
How do Python modules and imports work?
A module is any .py file. Importing it executes the file (once per interpreter session; subsequent imports reuse the cached version from sys.modules) and makes its names available in the importing namespace.
# Importing the whole module — access via module.name
import math
print(math.sqrt(16)) # 4.0
# Importing specific names — available without prefix
from math import sqrt, pi
print(sqrt(25)) # 5.0
# Import with alias — avoid name clashes or shorten long names
import numpy as np
import pandas as pd
# Star import — pulls all public names (avoid in production code)
from math import *Python looks for modules in this order: (1) built-in modules compiled into the interpreter, (2) sys.modules cache, (3) directories listed in sys.path — which includes the directory of the script being run, PYTHONPATH env var locations, and site-packages.
A package is a directory containing an __init__.py file (can be empty). Nested packages create a hierarchy: from mypackage.utils import helper. Python 3.3+ introduced namespace packages (no __init__.py needed), but regular packages with __init__.py are still the norm.
The if __name__ == '__main__': guard at the bottom of a module lets you write code that runs when the file is executed directly but not when imported as a module. It is the standard way to write both importable modules and runnable scripts in the same file.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
