QuizLander
← جميع الاختبارات العامة

Python — Decorators, closures & async (advanced)

بواسطة Jude · 23/05/2026 · 108 مشاهدات · 0 مشاركة

Higher-order functions, decorators with/without args, closures, async/await, concurrency models. 20 questions.
20
الأسئلة
🇬🇧 English
اللغة
صعب
الصعوبة
ابدأ الاختبار (كضيف أو بحساب)
مشاركة كصورة

أسئلة الاختبار

  1. 1. What does a decorator do?
    1. Adds type hints
    2. Wraps a function/class to return a (usually new) callable
    3. Compiles the function to C
    4. Renames the function at runtime
  2. 2. Why use functools.wraps?
    1. Thread safety
    2. Copies __name__, __doc__, __wrapped__ from the wrapped function
    3. Deep-copies arguments
    4. Memoizes results
  3. 3. What is printed?
    def make_counter():
        n = 0
        def inc():
            nonlocal n
            n += 1
            return n
        return inc
    
    c = make_counter()
    print(c(), c(), c())
    1. 1 1 1
    2. 1 2 3
    3. 0 1 2
    4. Error
  4. 4. Which decorator caches results of a pure function?
    1. @functools.lru_cache
    2. @staticmethod
    3. @property
    4. @dataclass
  5. 5. What does this print?
    import asyncio
    
    async def main():
        return 42
    
    print(type(main()))
    1. <class 'int'>
    2. <class 'coroutine'>
    3. <class 'function'>
    4. <class 'Future'>
  6. 6. Which is true about asyncio?
    1. Runs on multiple OS threads
    2. Cooperative single-threaded event loop — concurrency comes from await points
    3. Bypasses the GIL for CPU-bound code
    4. Linux-only
  7. 7. How do you run two coroutines concurrently and wait for both?
    1. await a; await b
    2. await asyncio.gather(a, b)
    3. asyncio.run(a); asyncio.run(b)
    4. asyncio.sleep(a, b)
  8. 8. What does this decorator do?
    def retry(n):
        def deco(fn):
            def wrapper(*a, **k):
                for _ in range(n):
                    try:
                        return fn(*a, **k)
                    except Exception:
                        pass
                return None
            return wrapper
        return deco
    1. Retries up to n times, swallowing exceptions; returns None on total failure
    2. Calls once and ignores errors
    3. Times the function
    4. Caches the result
  9. 9. Difference between threads and asyncio tasks for I/O-bound work?
    1. Threads are always faster
    2. Asyncio tasks are typically lighter and explicit at await points; threads are preemptive and heavier
    3. Same thing
    4. Threads can't do networking
  10. 10. Which best represents a class-based decorator?
    1. Class with __init__ and __call__
    2. Class with __enter__/__exit__
    3. Class with __iter__
    4. Class with __getattr__
  11. 11. What does this print?
    def stack(*decos):
        def apply(fn):
            for d in reversed(decos):
                fn = d(fn)
            return fn
        return apply
    
    def A(fn):
        def w(*a, **k): print("A"); return fn(*a, **k)
        return w
    def B(fn):
        def w(*a, **k): print("B"); return fn(*a, **k)
        return w
    
    @stack(A, B)
    def f(): print("f")
    
    f()
    1. f
    2. A B f
    3. B A f
    4. A f B
  12. 12. What does this output?
    import asyncio
    
    async def slow():
        await asyncio.sleep(0)
        return 1
    
    async def main():
        t = asyncio.create_task(slow())
        print("scheduled")
        return await t
    
    print(asyncio.run(main()))
    1. 1
    2. scheduled then 1
    3. 1 then scheduled
    4. Error
  13. 13. What's wrong with mixing time.sleep(5) inside an async function?
    1. Nothing
    2. It blocks the entire event loop, defeating asyncio's purpose; use await asyncio.sleep(5)
    3. It is faster than asyncio.sleep
    4. Raises a runtime error
  14. 14. What does functools.partial(f, 1, b=2) do?
    1. Calls f(1, b=2) immediately
    2. Returns a callable with 1 and b=2 pre-bound
    3. Creates a new function with default 1 only
    4. A no-op
  15. 15. Which is true about the GIL in CPython?
    1. Removed in 3.10
    2. Allows multiple Python bytecodes to execute simultaneously on multiple threads
    3. Ensures only one thread executes Python bytecode at a time; doesn't help CPU-bound multi-threading
    4. Only present on Windows
  16. 16. What is an async with?
    1. Syntax error
    2. Context manager that uses awaitable __aenter__/__aexit__
    3. Tries the block asynchronously
    4. Same as with
  17. 17. What does this print?
    import asyncio
    
    async def first():
        await asyncio.sleep(0.01)
        return "first"
    
    async def second():
        return "second"
    
    async def main():
        for c in asyncio.as_completed([first(), second()]):
            print(await c)
    
    asyncio.run(main())
    1. first then second
    2. second then first
    3. Always alphabetical
    4. Both at once
  18. 18. How do you cancel an asyncio task safely?
    1. task.cancel() and await it, handling CancelledError
    2. del task
    3. task.kill()
    4. Set task.done = True
  19. 19. What is the purpose of contextvars.ContextVar?
    1. Replace global variables for sync code
    2. Carry per-task contextual state across await boundaries in asyncio
    3. Improve dict lookup speed
    4. Schedule background tasks
  20. 20. Which decorator preserves the original signature for help/IDE introspection on the wrapped function?
    1. Hand-written wrapper without functools.wraps
    2. Wrapper using @functools.wraps(fn)
    3. Using *args, **kwargs alone
    4. Using lru_cache
أجب عن الأسئلة واعرف نتيجتك

التعليقات

سجّل الدخول للتعليق.

جارٍ التحميل…