🐍 Python for Everyone

← Back to challenges

Chapter 11 Interview Prep 20 min read

Interview Questions: Modules & Packages

Every Python codebase, however small, starts with a block of import statements — which makes this chapter's material come up constantly in real interviews, usually as quick "do you actually understand what's happening" checks rather than deep algorithm questions. This set covers import x vs. from x import y, why from module import * makes senior reviewers wince, module caching (why a module's top-level code only ever runs once), the module-vs-package distinction, why the standard library needs no installer while third-party packages do, random.seed() for reproducible tests, naive vs. aware datetimes at a conceptual level, and circular imports as a real-world gotcha.

1 What's the practical difference between import math and from math import sqrt?

import math brings the whole module into scope under the name math, and every name inside it has to be reached with a dotted prefix: math.sqrt(16). from math import sqrt instead pulls just the one name sqrt directly into the current file's namespace, callable on its own as sqrt(16) with no prefix at all. The tradeoff is readability versus brevity: math.sqrt makes it obvious at every call site exactly which module a function came from, which matters a lot once a file imports from several modules; from math import sqrt is shorter to type and read when a name is used constantly throughout a file. Neither is "more correct" in general — it's a call about how many other imported names might create ambiguity in that specific file.

Treating the two as functionally identical with no tradeoff, or being unable to say what would break if two different modules imported via from x import * both happened to define a function with the same name.

"If a file has both import math and from math import sqrt, are math.sqrt(4) and sqrt(4) the same function?" (Yes — both names point at the identical function object inside the one loaded math module; there's only ever one sqrt, just reachable under two different local names.)

2 Why is from module import * discouraged, even though it works?

from module import * dumps every public name from a module directly into the current namespace with no prefix and, critically, no visible list of what just got imported. Two problems follow from that: first, months later (or for anyone else reading the file), it's unclear at a glance which module a given name actually came from, since there's no module. prefix anywhere to check; second, it can silently overwrite an existing name already in use in that file — if the file already had its own sum or id variable, an unlucky import * from a module that also defines something by that name would quietly replace it, with no error or warning. Both problems get worse as more import * lines pile up in the same file, since there's no longer any single place to check where a given name came from. Nearly every Python style guide, including PEP 8, recommends against it for exactly these reasons.

Treating import * as just a stylistic preference for shorter code, without being able to name the specific "which module did this come from" and "silent overwrite" risks it introduces.

"A file defines def sqrt(x): return 'custom' and later does from math import *. What does calling sqrt(4) return after that?" (2.0 — the wildcard import silently replaced the file's own sqrt with math's version, with no warning that the name collided.)

3 If three different files in the same program all do import math, does math's code run three separate times?

No — Python only actually loads and executes a module's top-level code the first time it's imported anywhere in a running program. Every subsequent import math, no matter which file it appears in or how many times it appears, just reuses the same already-loaded module object from an internal cache (sys.modules); it doesn't re-run the module's code again. This is why importing the same module from many files across a larger project is completely normal and carries essentially no performance cost, and it's also why a module with meaningful top-level code (not just defs) — like a print statement or a counter that increments at import time — will only show that effect once, the first time it's imported, not once per file that imports it.

Assuming each new import statement re-executes the module from scratch, which would suggest (incorrectly) that importing a heavy module in many files is expensive, or that top-level module state resets between imports.

"A module named counter.py has one top-level line, print('loaded!'), outside any function. If two other files both do import counter, how many times does 'loaded!' print across the whole program?" (Once — the first import runs the module's top-level code and caches it; the second file's import counter just reuses that cached module without running it again.)

4 What's the difference between a module and a package?

A module is a single .py file — math, a hand-written helpers.py, anything that's just one file of Python code. A package is a folder containing multiple related modules, plus (traditionally) a special __init__.py file that tells Python "treat this folder as an importable package, not just an ordinary directory." A package is the next organizational step up once a project outgrows a handful of loose files: instead of one helpers.py with fifty unrelated functions, a package might group them into utils/formatting.py, utils/validation.py, and utils/calculations.py, all importable as utils.formatting, utils.validation, and so on.

Using "module" and "package" interchangeably when the distinction is actually being asked about, or not knowing that a package is fundamentally a folder (of modules) rather than a file.

"Is Python's own math a module or a package?" (A module — it's a single unit of functionality reached with one import math, not a folder of sub-modules the way a package would be.)

5 Why doesn't math need to be installed with a package manager, while a third-party library does?

math, datetime, and random are all part of Python's standard library — the collection of modules that ships bundled with Python itself, already present the moment Python is installed on a machine. No separate download or installer step is needed; import math just works anywhere a working Python interpreter exists. A third-party library (like requests or pandas) is written and maintained by someone outside Python's core team and distributed separately, so it has to be explicitly installed into that specific Python environment first — typically with pip, the standard package installer — before import can find it. The underlying import mechanism is identical either way; the difference is purely about whether the code was already sitting on disk as part of Python itself, or has to be fetched and installed first.

Assuming pip install is somehow required for every module, including standard-library ones, or being unable to name what distinguishes "standard library" from "third-party package" beyond "one needs installing."

"Would import random ever fail with a 'module not found' error on a normal Python install?" (No — random is standard library, bundled with every standard Python installation, so it's always available with no separate install step.)

6 What does random.seed() do, and why would a test suite ever want "random" numbers to be predictable?

random.seed(some_number), called once before any other random function runs, makes every subsequent "random" result in that program fully deterministic and repeatable — the same seed value always produces the exact same sequence of results, every time, on every machine. This matters for testing because a test needs a known, fixed expected value to assert against; a test that calls an unseeded random.randint(1, 6) and asserts the result equals some specific number would be flaky, passing or failing unpredictably from run to run. Seeding first removes that randomness for the duration of the test, without touching the actual production code path that uses random normally (unseeded) everywhere else.

Believing seeding makes the numbers "not really random" in a way that changes production behavior, rather than understanding it's a deliberate, temporary, test-only tool for reproducibility — real production code almost never calls random.seed() itself.

"If random.seed(42) is called, then random.randint(1, 100) is called once, will calling random.seed(42) again and calling random.randint(1, 100) a second time give the same result as the first?" (Yes — the same seed always restarts the exact same sequence of pseudo-random results from that point forward.)

7 What's the conceptual difference between a "naive" and an "aware" datetime?

A naive datetime stores a year/month/day (and optionally hour/minute/second) with no attached time zone information at all — it's just a plain calendar point with no notion of "relative to where." An aware datetime additionally carries a time zone, so it unambiguously represents one specific moment in universal time, correctly comparable to another aware datetime even if the two were created in different time zones. Every datetime.date and plain datetime.datetime object this course has used is naive — fine for calendar-day math like "how many days until this birthday," where time zone doesn't matter, but risky for anything that needs to compare exact moments in time across different locations (a global event's start time, a server log timestamped in UTC), where naive datetimes can silently be hours off from each other with no error raised.

Assuming all datetimes are automatically timezone-correct, or not knowing that comparing two naive datetimes that were actually meant to represent different time zones can silently give a wrong answer instead of an error.

"Why would a global company's server logs, timestamped from data centers in different countries, be risky to compare directly if stored as naive datetimes?" (Because naive datetimes carry no time zone, two timestamps that look identical, or a few hours apart, might actually represent different real moments in universal time — the comparison would run without error but could be silently wrong.)

8 What is a circular import, and why does it cause problems?

A circular import happens when module A imports module B, and module B (directly, or through some chain of other modules) imports module A right back — a loop. Because a module's top-level code only fully finishes running once, per Sub-topic 1's caching behavior, if A is still in the middle of its own top-level execution when it triggers B's import, and B immediately tries to import A back, Python hands B a half-finished version of A — whatever names A had already defined before the import of B happened, and nothing after. The result is usually an ImportError ("cannot import name X") or an AttributeError on a name that genuinely exists in A, just not yet at that point in A's execution. It's a real-world gotcha specifically because it often doesn't show up until a project has grown to several interdependent files, and the fix is usually restructuring which module owns which shared logic (or moving the import inside a function so it happens later, after both modules have finished loading) rather than anything to do with the imported code itself being wrong.

Assuming circular imports simply "don't work at all" (they sometimes do, if the needed name happens to already be defined by the time the loop crosses back), or having no explanation beyond "it's a common error," without being able to describe why the timing of top-level execution is the actual cause.

"Module a.py does import b as its very first line, and b.py does import a as its very first line. If something else imports a first, what's the practical symptom?" (Likely an ImportError or AttributeError when b tries to use something from a that hasn't been defined yet — a's import of b ran before a itself had defined anything, so b's attempt to import back from a finds an incomplete module.)

9 What does as actually do in an import statement, and when is it genuinely useful versus just noise?

as gives whatever is being imported — a whole module (import math as m) or one specific name (from math import sqrt as square_root) — a different local name in the current file. It's genuinely useful in two situations: shortening a long or awkward module name that gets used constantly (common with heavily-used third-party libraries), or avoiding a naming collision when two different modules would otherwise both want to be called the same thing in one file. It becomes noise when it's used without either reason — renaming math to some unrelated single letter with no length or collision justification just makes the code harder to read, since math.sqrt is already about as short and clear as it gets.

Renaming imports habitually with no real reason, which strips away the readability benefit of a clear, recognizable module name for no actual gain.

"Does import math as m import a different, smaller version of the math module?" (No — it imports the exact same, complete math module; only the local name used to refer to it in this file has changed, from math to m.)

10 What's the difference between math.floor(x), math.ceil(x), and Python's built-in round(x)?

math.floor(x) always rounds toward negative infinity (down, for a positive number), and math.ceil(x) always rounds toward positive infinity (up, for a positive number) — both are directional and don't care how close x is to the nearer whole number. Built-in round(x) instead rounds to the nearest whole number, in whichever direction is closer, and only reaches for math at all when a program needs to round in a specific, guaranteed direction regardless of how close the value is — a shipping calculator that must never round a package's billable weight down (favoring the shipper, not the customer) needs math.ceil specifically, since plain round() could round down and undercharge.

Assuming math.ceil and round are interchangeable, or not being able to give a concrete real-world case (like billing or inventory) where rounding in the wrong direction would actually cause a business problem.

"For a value of exactly 4.5, do math.floor, math.ceil, and round all agree?" (No — math.floor(4.5) is 4, math.ceil(4.5) is 5, and they represent two fixed directions, while round(4.5) picks the nearest value using its own rounding rule rather than a fixed direction.)

11 Why does subtracting two datetime.date objects give a timedelta instead of just a number?

A timedelta represents a span of time rather than a single point in time, and Python returns a full object for it (instead of a plain integer) because a span of time can itself be measured in more than one unit — days, but also, for full datetime objects, seconds and microseconds. Returning a timedelta object keeps all of that information intact and gives it useful attributes like .days, rather than the subtraction silently assuming "the caller definitely just wants days" and discarding everything else. In practice, most simple calendar-day calculations only ever read the .days attribute off the result, which is why it looks, at first glance, like date subtraction "just gives a number" — it actually gives an object, and .days is how that number gets pulled out of it.

Trying to use the result of a date subtraction directly as a number without .days (e.g. printing it expecting an integer), or not knowing a timedelta is an object with its own attributes rather than already being a plain number.

"Given gap = date2 - date1, what type is gap, and how do you get the plain number of days out of it?" (gap is a datetime.timedelta object; gap.days gives the plain integer number of days between the two dates.)

12 If a program needs to convert Celsius to Fahrenheit and round the result, why might that not need the math module at all?

Celsius-to-Fahrenheit is pure arithmetic — celsius * 9 / 5 + 32 — using only operators (*, /, +) that have been available since Chapter 2, with no square root, no directional rounding, and no constant like π involved anywhere. Rounding the final result to a sensible number of decimal places is built-in round(value, 2), not part of math at all. This is a useful interview instinct to demonstrate: reaching for import math reflexively on every numeric task, rather than recognizing when the built-in operators and functions already taught (arithmetic operators, round()) are entirely sufficient, is a sign of pattern-matching over understanding what math actually adds (square roots, directional rounding, trig, constants) beyond what Python already provides for free.

Importing math automatically for any calculation involving decimals or rounding, without checking whether the specific operation actually needs something math provides beyond ordinary arithmetic and the built-in round().

"Would computing a circle's area (πr²) have the same option of skipping math entirely?" (No — that specifically needs math.pi, since π isn't a Python built-in constant; arithmetic operators alone can't produce it.)

13 Can you import the same module under two different names in the same file, and would that cause any problems?

Yes — import math followed later by import math as m in the same file is perfectly legal; both names, math and m, end up pointing at the exact same underlying module object, since (per module caching) Python only ever loads math once regardless of how many names end up referring to it. There's no functional problem with this — math.sqrt(4) and m.sqrt(4) call the identical function either way. The real cost is purely readability: having two different names for the same module in one file makes it harder for a reader to recognize both refer to the same thing, so in practice this is avoided by convention (pick one name per module per file) rather than by any technical restriction.

Assuming this would cause a runtime error, or believing it creates two separate copies of the module in memory rather than two names pointing at the one cached module.

"After import math and import math as m both run, is math is m True or False?" (True — both names refer to the identical cached module object, since a module is only ever loaded once.)

Rapid-Fire Review

Quick recall check — fill in each blank and hit Check.

🎉 Perfect score — you're ready to talk about this chapter in an interview.
← Challenges Build the Project →