CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-wtfpython

Educational collection of surprising Python code snippets that demonstrate counter-intuitive behaviors and language internals

Overall
score

93%

Overview
Eval results
Files

task.mdevals/scenario-2/

Scope Analyzer

A Python utility that demonstrates variable scope behavior and closure handling.

Capabilities

Closure Variable Capture

  • Given an integer n=5, returns a list of 5 functions where calling the i-th function returns the integer i (0-indexed) @test
  • Given a list [10, 20, 30], returns a list of 3 lambda functions where the i-th lambda returns the i-th value from the original list @test

Scope Modification

  • Given initial value 10 and increment 5, uses an inner function with nonlocal to modify the enclosing variable and returns 15 @test
  • When called with value 42, sets the module-level variable 'counter' to 42 using the global keyword @test

Scope Error Handling

  • When a function attempts to print a variable x before assigning to x in the same scope, raises UnboundLocalError @test

Implementation

@generates

API

def create_closure_functions(n: int) -> list:
    """
    Creates a list of n functions where each function returns its index.
    Must properly handle closure variable capture.

    Args:
        n: Number of functions to create

    Returns:
        List of functions, where the i-th function returns i
    """
    pass

def create_lambda_closures(values: list) -> list:
    """
    Creates a list of lambda functions that capture values from the input list.

    Args:
        values: List of values to capture

    Returns:
        List of lambda functions, where the i-th lambda returns values[i]
    """
    pass

def modify_with_nonlocal(initial: int, increment: int) -> int:
    """
    Uses an inner function to modify an enclosing scope variable.

    Args:
        initial: Initial value of the enclosing variable
        increment: Amount to increment by

    Returns:
        The modified value after incrementing
    """
    pass

def set_global_counter(value: int) -> None:
    """
    Sets the module-level variable 'counter' to the given value.

    Args:
        value: Value to set for the global counter
    """
    pass

def trigger_unbound_local_error() -> None:
    """
    Demonstrates UnboundLocalError by reading before assignment.

    Raises:
        UnboundLocalError: Always raised when called
    """
    pass

Dependencies { .dependencies }

Python Standard Library { .dependency }

Uses built-in Python features for scope and closure demonstration. No external dependencies required.

Install with Tessl CLI

npx tessl i tessl/pypi-wtfpython

tile.json