Python interview questions
A Python interview rarely asks you to recite syntax. It asks what a generator actually is, why a default argument of [] bites, or what the bare * in a signature does — the things you use every day without having to say out loud.
These questions run from that first layer (lists against tuples, *args and **kwargs, shallow and deep copies) to the corners modern codebases lean on: pathlib, match, typing with Literal and Iterable.
All 31 are the free Foundation level of the Python topic in GapfyreSWE. Try each one before you open its answer.
-
What is a Python generator and what keyword creates one?
- A built-in that creates random values, defined with @generator
- A function using yield that produces values lazily, one at a time
- A decorator that makes a regular function run asynchronously
- A class that extends list to generate values on demand, created with generate()
Show the answer
B. A function using yield that produces values lazily, one at a time
A generator is a function that yields values one at a time using the yield keyword, pausing execution between yields. It returns a generator object (iterator). Generators are memory-efficient for large sequences because values are produced lazily rather than stored in memory all at once.
-
What is the difference between a list and a tuple in Python?
- Lists are ordered; tuples are unordered
- Lists use less memory than tuples for the same data
- Lists are mutable; tuples are immutable
- Tuples can hold mixed types; lists cannot
Show the answer
C. Lists are mutable; tuples are immutable
Lists are mutable — elements can be added, removed, or changed. Tuples are immutable — once created they cannot be modified. Tuples are slightly faster, can be used as dictionary keys (if their contents are hashable), and signal intent that the data should not change.
-
What does duck typing mean in Python?
- All Python objects inherit from a common Duck base class
- Python converts objects to strings automatically when needed
- An object's suitability is determined by its methods and attributes, not its type
- Python uses dynamic typing, so all variables are typed as "duck" until assigned
Show the answer
C. An object's suitability is determined by its methods and attributes, not its type
Duck typing is a concept where the type or class of an object is less important than the methods and attributes it defines. If an object has the required method, it can be used — "if it walks like a duck and quacks like a duck, it's a duck." Python does not require explicit interface declarations.
-
What is the difference between *args and **kwargs in a Python function definition?
- Both collect the same arguments — the double asterisk just enforces keyword-only syntax
- *args unpacks a list into function arguments; **kwargs unpacks a dict
- *args collects keyword arguments; **kwargs collects positional arguments
- *args collects positional arguments; **kwargs collects keyword ones
Show the answer
D. *args collects positional arguments; **kwargs collects keyword ones
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. Together they allow a function to accept an arbitrary number of positional and keyword arguments, making APIs flexible and enabling decorator pass-through.
-
What is the difference between a shallow copy and a deep copy of a Python object (e.g. via
copy.copy()vs.copy.deepcopy())?- They are identical;
deepcopyis only a performance-optimized alias forcopy - A shallow copy shares nested objects with the original; a deep copy recursively copies them
- A deep copy shares references while a shallow copy is fully independent
- A shallow copy only works on immutable types; a deep copy is required for any mutable type
Show the answer
B. A shallow copy shares nested objects with the original; a deep copy recursively copies them
A shallow copy creates a new outer container, but the elements inside it are the same objects (by reference) as in the original — so mutating a nested mutable object (like a list inside a list) through the copy also changes the original. A deep copy recursively copies every nested object too, producing a fully independent structure where nothing is shared with the original at any level, at the cost of more time and memory to construct.
- They are identical;
-
What is the syntax and result type of a Python dictionary comprehension, as opposed to a list comprehension?
- A dict comprehension uses square brackets like a list comprehension, differing only in the presence of a colon
- Dict comprehensions cannot include a conditional (
if) clause, unlike list comprehensions - They produce the same result type; the syntax difference is purely cosmetic
- A dict comprehension uses braces and key: value; a list comprehension uses brackets
Show the answer
D. A dict comprehension uses braces and key: value; a list comprehension uses brackets
A dict comprehension uses curly braces with a
key: valuepair per iteration —{k: v for k, v in pairs}— and produces a dict. A list comprehension uses square brackets with a single expression per iteration —[v for v in items]— and produces a list. Both share the same underlying for/if clause structure, just wrapped in different brackets and producing a different container with correspondingly different element shapes (key-value pairs versus single values). -
What is a Python
lambda, and how does it differ from a function defined withdef?- A lambda can only take zero arguments;
defis needed for parameters - Lambdas execute faster than
defbecause they skip bytecode compilation - A lambda is an anonymous single-expression function; def takes full bodies
- A lambda can contain multiple statements and a full body, like
def
Show the answer
C. A lambda is an anonymous single-expression function; def takes full bodies
A lambda is a small, anonymous, single-expression function —
lambda x: x * 2— that evaluates and returns exactly one expression, with no statements, no name of its own (unless assigned to a variable), and no docstring. Adeffunction can contain any number of statements, multiple return points, a docstring, and default naming, making lambdas suited only for short, throwaway callbacks (like akey=function passed tosorted()) rather than general-purpose function definitions. - A lambda can only take zero arguments;
-
In a Python
try/except/else/finallyblock, what specifically runs in theelseclause versus thefinallyclause?elseandfinallyboth run unconditionally regardless of whether an exception occurred- else runs only if the try block raised nothing; finally runs unconditionally afterwards
elseruns only when an exception is caught;finallyonly runs when no exception occursfinallyis skipped if the exception is unhandled; onlyelseruns in that case
Show the answer
B. else runs only if the try block raised nothing; finally runs unconditionally afterwards
The
elseclause runs only if thetryblock completed with no exception raised at all — it is a place to put code that should run on the success path but that you don't want theexceptblock accidentally catching exceptions from. Thefinallyclause runs unconditionally, whether thetryblock succeeded, raised a handled exception, or raised an exception that propagated past everyexceptclause — making it the right place for cleanup that must always happen (like closing a file), regardless of outcome. -
What is the difference between an iterable and an iterator in Python?
- Only built-in types like lists and dicts can be iterables; only user-defined classes can be iterators
- An iterator can be re-used indefinitely from the start; an iterable is single-use
- An iterable can produce a fresh iterator each time; an iterator is single-use and raises StopIteration
- They are the same thing; "iterator" is just an informal name for any iterable object
Show the answer
C. An iterable can produce a fresh iterator each time; an iterator is single-use and raises StopIteration
An iterable is any object that implements
__iter__(), which returns an iterator — a list, a dict, a string, and many other objects are iterable, but callingiter()on them fresh each time is what actually produces a new iterator. An iterator is the object that implements__next__(), producing one value at a time and raisingStopIterationwhen exhausted; unlike an iterable, an iterator is generally single-use — once exhausted, it stays exhausted, while a fresh iterator can always be obtained again from the original iterable. -
What does
collections.Counterdo, and what problem does it solve compared to manually counting occurrences with a plain dict?- It is functionally identical to a plain dict, differing only in its
repr()output - It is a thread-safe lock used to prevent race conditions when incrementing a shared counter variable
- Counter can only count integers, not arbitrary hashable objects like strings or tuples
- A dict subclass that tallies frequencies, treats a missing key as 0, and adds most_common() for convenience
Show the answer
D. A dict subclass that tallies frequencies, treats a missing key as 0, and adds most_common() for convenience
Counteris a dict subclass specialized for counting hashable items:Counter(some_iterable)tallies how many times each element appears in one call, and looking up a key that has never been seen returns 0 instead of raising a KeyError, so incrementing a fresh key needs no manual existence check. It also comes with convenience methods likemost_common()for ranking by frequency, which manually maintaining a plain dict of counts does not give you without extra code. - It is functionally identical to a plain dict, differing only in its
-
What is an f-string in Python, and what problem does it solve compared to older
%-formatting or.format()?- It embeds the expression in the literal, more concise than % or .format()
- An f-string only formats floating-point numbers, embedding no expressions
- f-strings work only with string literals, never with template variables
- f-strings are evaluated lazily at first use and then cached
Show the answer
A. It embeds the expression in the literal, more concise than % or .format()
An f-string (
f"Hello, {name}!") lets an expression be embedded directly inside a string literal, evaluated and interpolated in place at the point where it appears — more concise and readable than%-formatting's separate format-string-plus-tuple, or.format()'s indexed/named placeholders that are visually disconnected from the values being substituted. Because the expression sits right where the substitution happens, an f-string is generally easier to read and less error-prone (fewer chances to mismatch a placeholder with the wrong positional argument) than either older style. -
What does
[x * 2 for x in nums if x > 0]do, and why is it preferred to the loop it replaces?- Modifies nums in place, which is why the result does not need to be assigned to anything
- Returns a generator, so the doubling happens lazily as the result is iterated
- Builds a new list from the items passing the filter — clearer and faster than an accumulate-and-append loop
- Is compiled to a C loop by the interpreter, which is the only reason it runs faster
Show the answer
C. Builds a new list from the items passing the filter — clearer and faster than an accumulate-and-append loop
It builds a new list by applying the expression to each item that passes the condition — the same as an empty list, a for loop and an append, in one expression. It is preferred because the shape says what is being produced before you read the details, it keeps the result in one place rather than accumulating into a variable declared earlier, and it is measurably faster since the append is done by the interpreter rather than by a method call per item. The caution is nesting: past two clauses the loop is clearer.
-
What is a Python virtual environment and why is it used?
- A sandboxed process that prevents a running script from accessing the filesystem or the network at all
- A container image that bundles the interpreter together with the OS libraries needed for deployment
- A background process that automatically restarts a script whenever it crashes or exits unexpectedly
- An isolated set of installed packages per project, so dependencies do not conflict across projects
Show the answer
D. An isolated set of installed packages per project, so dependencies do not conflict across projects
A virtual environment is an isolated Python installation with its own site-packages directory, created with venv (or tools like virtualenv), so that packages installed for one project do not affect the system Python or any other project's dependencies. This lets two projects on the same machine depend on different, even conflicting, versions of the same library without either one interfering with the other.
-
One codebase writes
def find(id: int) -> User | None, another-> Optional[User]. What is the difference?- None: Optional[X] is shorthand for X | None, which Python 3.10 and later accept directly
- X | None is checked at runtime and raises TypeError, while Optional is only a hint for tools
- Optional allows any falsy value such as 0 or "", while X | None allows only None itself
- Optional means the argument may be omitted, while X | None means it may be passed as None
Show the answer
A. None: Optional[X] is shorthand for X | None, which Python 3.10 and later accept directly
None: they are the same type, and
Optional[int] == (int | None)is true.Optional[X]was always shorthand for "X or None", and from Python 3.10 the|union syntax can be used in annotations directly, so new code tends to writeX | Noneand drop the import. Either way the hint only documents that None is a possible result — nothing checks it at runtime — and a type checker then insists that callers handle the None before using the value as a User. -
Shapedefines@classmethod def unit(cls): return cls(1)and@staticmethod def helper(x).SquaresubclassesShape. What doesSquare.unit()return, and what doeshelperreceive?- A Shape, since a classmethod is bound to the class it is defined in; helper receives the instance
- A Square, but only if Square overrides unit; helper receives self like any other method
- A Square, since cls is the class it was called on; helper receives no implicit argument
- An error, since classmethods cannot be called on subclasses; helper receives the class
Show the answer
C. A Square, since cls is the class it was called on; helper receives no implicit argument
A
classmethodreceives the class it was called on ascls, soSquare.unit()builds a Square — which is why alternative constructors are classmethods, and why they keep working in subclasses. Astaticmethodreceives no implicit first argument at all, neither instance nor class; it is a plain function kept in the class's namespace, andSquare(3).helper(5)simply returned 10. Writingreturn Shape(1)in the constructor instead would hand every subclass a Shape. -
Code builds file paths with
os.path.joinand string slicing. What doespathlib.Pathoffer instead?- Validation that the file exists, since constructing a Path raises FileNotFoundError otherwise
- Cross-platform strings, since a Path is a str subclass that rewrites backslashes on Windows
- Path objects joined with / that expose parts like suffix and parent, plus methods to read and glob
- Faster file access, since a Path keeps the file open and caches all of its contents after the first read
Show the answer
C. Path objects joined with / that expose parts like suffix and parent, plus methods to read and glob
A
Pathis an object rather than a string:/joins parts (Path("/srv/app") / "data" / "users.csv"), and the pieces are attributes —.suffixwas ".csv",.stem"users",.parent.name"data" — so nobody slices strings at the last dot or slash. It also carries the operations:read_text(),write_text(),exists(),mkdir(parents=True),glob("*.py"). It uses the right separator on each platform, and the functions that take paths accept a Path, so most ofos.pathis no longer needed. -
A module does
log = logging.getLogger(__name__)and laterlog.debug("value %s", obj). Why__name__, and why the%srather than an f-string?- __name__ names the logger by module for configuration; %s defers formatting until it is emitted
- __name__ hides the module from the output; %s writes the value in the record's raw binary form
- __name__ makes the logger a singleton per process; %s is required because logging rejects f-strings
- __name__ sets the level from an environment variable; %s pads the value to a fixed width
Show the answer
A. __name__ names the logger by module for configuration; %s defers formatting until it is emitted
getLogger(__name__)names the logger after the module —myapp.billing— so configuration can target a package or one module by its dotted name, and log lines say where they came from. Passing the value as an argument defers formatting until a handler actually emits the record: with DEBUG off, which it is by default since an unconfigured logger's effective level is WARNING,str(obj)was never called for the%sform, while the f-string built its message regardless. Linters such as Ruff flag f-strings in logging calls for this reason. -
What do the bare
*indef f(a, *, flag=False)and the/indef g(a, b, /, c)do?- * makes the remaining parameters required, and / makes the preceding ones read-only inside f
- Both mark optional parameters, with * for keywords that default to None and / for defaults of 0
- * collects extra positional arguments into a tuple, and / divides the arguments as a float
- After * parameters must be passed by keyword; before / they must be passed by position
Show the answer
D. After * parameters must be passed by keyword; before / they must be passed by position
Parameters after a bare
*are keyword-only:f(1, flag=True)works andf(1, True)is a TypeError, "f() takes 1 positional argument but 2 were given" — which stops a call site reading as an unexplainedTrue. Parameters before/are positional-only:g(1, 2, c=3)works andg(a=1, b=2, c=3)fails with "got some positional-only arguments passed as keyword arguments". The first makes calls readable; the second leaves a function free to rename its parameters without breaking callers. -
A
matchon a colour hascase RED:as its first case, withRED = 1defined at module level. Why does it fail to compile, and how is a constant matched?- Names in patterns are compared by identity, and 1 is not the same object as RED
- A bare name captures any value, so RED would match everything; use a dotted name such as Color.RED
- Module-level names are not visible inside a match statement, so RED must be passed in as a parameter first
- match only accepts literals, so a constant must be written out as case 1 instead of a name
Show the answer
B. A bare name captures any value, so RED would match everything; use a dotted name such as Color.RED
In a pattern, a bare name is a capture, not a lookup:
case RED:would bind any value to a new variable called RED, so it matches everything — and as a first case it makes the rest unreachable, which Python refuses: "name capture 'RED' makes remaining patterns unreachable". Placed last, it silently swallowed everything. A constant has to be a dotted name, such ascase Color.RED:. The other patterns destructure:{"type": "point", "x": x, "y": y} if x == yand[first, *rest]both matched in the harness. -
A function only loops over its argument. Why do typed codebases annotate it
items: Iterable[str], imported fromcollections.abc, rather thanitems: list[str]?- Iterable[str] converts the argument to an iterator on entry, so a list passed in is consumed only once
- collections.abc types are checked on every call at runtime, while list[str] is only read by checkers
- list[str] cannot be used in annotations before Python 3.12, so collections.abc is the portable spelling
- Iterable takes any iterable — tuple, set, generator — and lets the checker stop the function mutating it
Show the answer
D. Iterable takes any iterable — tuple, set, generator — and lets the checker stop the function mutating it
Annotate a parameter with the least the function needs.
list[str]promises a list, so mypy rejected passing a tuple;Iterable[str]accepted a list, tuple, set, generator or range alike, and mypy flaggeditems.append(...)inside the function, since an Iterable promises only that it can be looped over. Nothing changes at runtime: the function received the caller's own list object.collections.abcholds these abstract types — Iterable, Sequence, Mapping, Callable and the rest — and they work withisinstancetoo: a dict and a read-onlyMappingProxyTypewere both a Mapping, while the proxy was not a dict.list[str]itself has worked in annotations since Python 3.9. -
What does
json.loads(json.dumps({1: (2, 3)}))return, and why is it not equal to the original?- {'1': [2, 3]}: JSON keys are strings, and its only array type comes back as a list
- A TypeError from dumps, since JSON cannot represent tuples or integer dictionary keys
- {1: [2, 3]}: the int key survives, and only the tuple turns into a list on the way
- {1: (2, 3)} unchanged, since json records each value's Python type alongside it
Show the answer
A. {'1': [2, 3]}: JSON keys are strings, and its only array type comes back as a list
It returned
{'1': [2, 3]}. JSON objects have only string keys, sojson.dumpsturned the int key 1 into "1", and JSON has one array type, so the tuple became a list; nothing records what either was, sojson.loadscannot restore them. Other quiet changes: a dict with both 1 and "1" as keys was written as{"1": "a", "1": "b"}and came back holding only the last; a tuple key raised TypeError ("keys must be str, int, float, bool or None"); andfloat("nan")was written asNaN, which is not valid JSON, unlessallow_nan=Falsemakes it an error. Types beyond these — sets, datetimes, dataclasses — raise TypeError rather than change. -
A
RateLimiterinstance is used like a function:allow = RateLimiter(2), thenallow(user). What makes an instance callable, and why use one instead of a closure?- Assigning a function to self.__call__ in __init__; the instance then keeps its state in a closure
- A __call__ method on its class; the instance keeps its state in attributes a caller can read
- Any class with __init__ is callable; calling an instance runs __init__ again with new arguments
- Inheriting from types.FunctionType, which gives the instance the calling convention of a def
Show the answer
B. A __call__ method on its class; the instance keeps its state in attributes a caller can read
A
__call__method on the class:allow(user)runs it withallowas self, andcallable(allow)is True. An instance keeps its state as attributes, soallow.callsread 3 after three calls, where a closure's counter is hidden — the closure had nocallsattribute — and the class can carry other methods, a repr and configuration. That is why class-based decorators, middleware and strategy objects use it. The method has to be on the class: settingp.__call__ = lambda: "hi"on an instance leftcallable(p)False, andp()raised "'Plain' object is not callable", since Python looks special methods up on the type rather than the instance. -
A function is annotated
def open_it(path: str, mode: Literal["r", "w"]). What happens toopen_it("a", "x"), and tom = "w"followed byopen_it("a", m)?- The checker rejects "x" but accepts m, since it holds "w"; at runtime the "x" call raises ValueError
- The checker rejects both: "x" is not allowed, and m is inferred as str; neither fails at runtime
- Both are accepted: Literal is documentation only, and checkers treat it the same as a plain str
- Both raise TypeError at the call, because Literal is the one annotation the interpreter enforces
Show the answer
B. The checker rejects both: "x" is not allowed, and m is inferred as str; neither fails at runtime
Literalnarrows a type to specific values, so mypy rejected the first call: Argument 2 has incompatible type "Literal['x']"; expected "Literal['r', 'w']". At runtime nothing checks it — the same call ran and returned 'x'. The second call surprises people: mypy rejected it too, becausem = "w"infersmasstr, which could be any string. Annotatingm: Final = "w"orm: Mode = "w"keeps the literal type, and both passed. Literals are how string and int options are typed — modes, log levels, HTTP methods — and a checker treats them like an enum: anif/elifcovering both values needed no fallback return, and adding a third value made mypy report "Missing return statement".typing.get_argsreturns the values, ('r', 'w'), for code that wants to validate at runtime. -
Which line gives every
Orderits own emptyitemslist when none is passed in?from dataclasses import dataclass, field @dataclass class Order: id: str ___items: list[str] = []items: list[str] = field(default_factory=list())items: list[str] = field(default=[])items: list[str] = field(default_factory=list)
Show the answer
D.
items: list[str] = field(default_factory=list)A default is evaluated once, when the class is defined, so a
[]default would be one list shared by every instance — the mutable-default bug a plaindef __init__(self, tags=[])still has: appending through one instance showed up in the next.@dataclassrefuses it as the class is defined: "mutable default <class 'list'> for field items is not allowed: use default_factory", andfield(default=[])raised the same.default_factorytakes a zero-argument callable that is called for each new instance, so two Orders had separate lists. Passinglist()instead oflisthands it an already-built list: the class was defined, thenOrder("1")failed with "'list' object is not callable". Dict and set defaults are refused the same way. -
A script reads its settings with
tomllib.load(open("pyproject.toml"))and fails withTypeError. What is wrong, and what cantomllibnot do?- The file must be opened with encoding="utf-8"; and tomllib cannot parse nested [tool.*] tables
- load needs a binary file, open(..., "rb"); and tomllib only parses, with no dump to write TOML
- pyproject.toml is reserved for build tools; tomllib reads only other .toml files and never writes
- tomllib needs a str path, not a file object; and it cannot read TOML dates, which stay as strings
Show the answer
B. load needs a binary file, open(..., "rb"); and tomllib only parses, with no dump to write TOML
tomllib.loadtakes a file opened in binary mode — "File must be opened in binary mode, e.g. useopen('foo.toml', 'rb')", even withencoding="utf-8"given — because it decodes the bytes as UTF-8 itself, TOML being UTF-8 by definition.with open("pyproject.toml", "rb") as f:worked, andtomllib.loadstakes a str, such asPath(...).read_text(). The result is plain dicts, lists and scalars, with TOML dates asdatetimeobjects. tomllib only reads: it has nodumpordumps, so writing TOML needs a third-party package. It is in the standard library from Python 3.11 — on 3.9 the import raised ModuleNotFoundError — and code supporting older versions falls back toimport tomli as tomllib, which behaved the same. -
A library that supports Python 3.9 and later imports
overrideandTypeIsfromtyping_extensionsrather thantyping. What istyping_extensions, and why import from it?- The older name of the typing module, kept so that code written for Python 2 still imports cleanly
- A type-checker plugin; the import is skipped at runtime, so it costs nothing and needs no install
- A standard-library module of experimental typing features, shipped with Python from 3.8 onwards
- A PyPI package backporting newer typing names, so one import works on every supported version
Show the answer
D. A PyPI package backporting newer typing names, so one import works on every supported version
It is a package on PyPI — not part of the standard library, so it is a declared dependency — that backports new typing features to older Pythons.
typinghad nooverrideon 3.9 or 3.11 and noTypeIson 3.12, whiletyping_extensionsprovided both on 3.9 and on 3.12, so the library writes one import that works on every Python it supports. Wheretypingalready has the name, it usually re-exports the standard object — on 3.14typing_extensions.override is typing.overridewas True — though some it reimplements to carry newer behaviour: itsTypedDictwas not typing's on 3.14 or 3.12. Type checkers understand both spellings, andoverrideworks at runtime too, setting__override__on the method. -
Which line completes this, so capitals maps each city back to its country code?
codes = {"GB": "London", "FR": "Paris"} ___capitals = {city: code for code, city in codes.items()}capitals = dict(zip(codes, codes.values()))capitals = {city: code for code, city in codes}capitals = {city: code for city, code in codes.items()}
Show the answer
A.
capitals = {city: code for code, city in codes.items()}items() yields (key, value) pairs, so unpacking them as code, city and writing city: code swaps each pair. Unpacking them as city, code just renames them, so the dict comes out unchanged, and zip over the keys and values rebuilds the original too. Iterating the dict itself yields only its keys, so each two-letter code is unpacked into its two characters: {'B': 'G', 'R': 'F'}.
-
Which line completes this, so label is "£1,234.50"?
price = 1234.5 ___label = f"£{price:.2f}"label = f"£{price:,.2f}"label = f"£{price:2f,}"label = f"£{price:,}"
Show the answer
B.
label = f"£{price:,.2f}"After the colon in an f-string comes a format spec. A comma adds thousands separators, and .2f gives fixed-point with exactly two decimals, in that order: ,.2f. Without the comma you get £1234.50, and without .2f the float prints as it is, £1,234.5. The parts must come in the order the spec defines, separator before precision, so 2f, raises ValueError: Invalid format specifier.
-
Which line completes this, so top is [("the", 3)]?
words = "the cat the dog the end".split() ___top = Counter(words).most_common()[0]top = sorted(Counter(words))[:1]top = max(Counter(words))top = Counter(words).most_common(1)
Show the answer
D.
top = Counter(words).most_common(1)Counter tallies the words, and most_common(n) returns a list of the n commonest (item, count) pairs, highest first. most_common()[0] is the right pair, but as a tuple rather than a one-item list. max over a Counter compares its keys, the words themselves, so it returns the alphabetically largest word, here "the" by coincidence, without a count. sorted(...)[:1] takes the alphabetically first word, "cat".
-
Which decorator completes this, so Temp.from_fahrenheit(212) gives a Temp at 100 °C, and a subclass's call gives an instance of the subclass?
class Temp: def __init__(self, celsius): self.celsius = celsius ___ def from_fahrenheit(cls, f): return cls((f - 32) * 5 / 9)@staticmethod@contextlib.contextmanager@property@classmethod
Show the answer
D.
@classmethod@classmethod passes the class the method was called on as cls, so cls(...) builds a Temp from Temp and a subclass from a subclass. That is what makes it the usual way to write an alternate constructor. @staticmethod passes nothing implicit, so 212 lands in cls and f is missing: TypeError. @property makes Temp.from_fahrenheit a property object, which cannot be called. @contextmanager wraps it as a plain function, missing its argument the same way.
-
A try statement has except, else and finally clauses, and the try body raises nothing. Put the parts that run in order.
- The else block
- The finally block
- The try block
Show the answer
- The try block
- The else block
- The finally block
With no exception, the except clause is skipped. The else clause runs next, which is its whole point: code that should only run if the try succeeded, kept outside the try so its own errors are not caught by that except. finally runs last, whatever happened, including after a return or an uncaught exception.
Practise the rest in the app
GapfyreSWE has 53 more Python questions at Intermediate and Advanced level, and over 4,700 across 80+ topics. It works offline and asks for no account.