Python Functions and Scope 4 — Questions and Answers
Question 1: What does the `functools.wraps` decorator do?
- Speeds up function execution
- Copies the wrapped function's metadata to the wrapper function (Correct answer)
- Prevents the function from being called more than once
- Converts the function to a coroutine
Correct answer: Copies the wrapped function's metadata to the wrapper function
`functools.wraps` copies attributes like `__name__` and `__doc__` from the wrapped function to the decorator wrapper, preserving introspection.
Question 2: What is the output of: `f = lambda x, y=2: x * y; print(f(3))`?
- 6 (Correct answer)
- 3
- 2
- TypeError
Correct answer: 6
`y` defaults to 2, so `f(3)` computes `3 * 2 = 6`.
Question 3: Which built-in function applies a function to every item in an iterable?
- apply()
- filter()
- map() (Correct answer)
- reduce()
Correct answer: map()
`map(func, iterable)` returns an iterator that applies `func` to each element of the iterable.
Question 4: When is a Python function's default argument value evaluated?
- Each time the function is called
- At function definition time (Correct answer)
- When the module is imported for the first time
- When the argument is first used inside the function body
Correct answer: At function definition time
Default values are evaluated once when the `def` statement is executed, not on each call — this is why mutable defaults can cause bugs.
Question 5: What does `inspect.signature(func)` return?
- The function's source code
- A Signature object describing the function's parameters (Correct answer)
- The function's return type
- The number of arguments
Correct answer: A Signature object describing the function's parameters
`inspect.signature` returns a `Signature` object that contains information about the function's parameters and their defaults.
Question 6: What is a generator function?
- A function that returns a list
- A function that uses `yield` to produce values lazily (Correct answer)
- A function that runs in a separate thread
- A function decorated with @generator
Correct answer: A function that uses `yield` to produce values lazily
A generator function contains at least one `yield` statement; calling it returns a generator iterator that produces values on demand.
Question 7: What happens when you call `sorted([3,1,2], key=lambda x: -x)`?
- [1, 2, 3]
- [3, 2, 1] (Correct answer)
- [2, 1, 3]
- TypeError
Correct answer: [3, 2, 1]
Negating each element makes `sorted` order by descending value, so the result is `[3, 2, 1]`.
What does the `functools.wraps` decorator do?