🔍 Code Extractor

class Generator

Maturity: 53

Generator is a specialized Callable wrapper class that wraps Python generator objects, providing controlled iteration with no arguments and no memoization.

File:
/tf/active/vicechatdev/patches/spaces.py
Lines:
606 - 628
Complexity:
moderate

Purpose

This class wraps Python generator objects (types.GeneratorType) to provide a standardized callable interface for generators within a parameter-based framework. It ensures generators are called without arguments, handles exceptions during iteration, and provides introspection capabilities through argspec. The class inherits from Callable and is designed to integrate with the param library's parameter system, treating generators as special callables that never cache their results.

Source Code

class Generator(Callable):
    """
    Generators are considered a special case of Callable that accept no
    arguments and never memoize.
    """

    callable = param.ClassSelector(default=None, class_ = types.GeneratorType,
                                   constant=True, doc="""
         The generator that is wrapped by this Generator.""")

    @property
    def argspec(self):
        return FullArgSpec(args=[], varargs=None, varkw=None, defaults=None, kwonlyargs=None, kwonlydefaults=None, annotations=None)

    def __call__(self):
        try:
            return next(self.callable)
        except StopIteration:
            raise
        except Exception:
            msg = 'Generator {name} raised the following exception:'
            self.param.warning(msg.format(name=self.name))
            raise

Parameters

Name Type Default Kind
bases Callable -

Parameter Details

callable: A Python generator object (types.GeneratorType) that will be wrapped by this class. This parameter is constant (cannot be changed after initialization) and must be a generator type. It represents the underlying generator that will be iterated when the Generator instance is called.

Return Value

When instantiated, returns a Generator instance that wraps the provided generator object. When the instance is called via __call__(), it returns the next value from the wrapped generator by calling next() on it. If the generator is exhausted, raises StopIteration. For other exceptions, logs a warning and re-raises the exception.

Class Interface

Methods

__call__(self) -> Any

Purpose: Advances the wrapped generator by one step and returns the next yielded value

Returns: The next value yielded by the wrapped generator. Type depends on what the generator yields. Raises StopIteration when the generator is exhausted, or re-raises any other exception after logging a warning.

argspec -> FullArgSpec property

Purpose: Provides introspection information about the callable signature, always returning an empty argument specification since generators accept no arguments

Returns: A FullArgSpec object with empty args list and all other fields set to None, indicating this callable takes no arguments

Attributes

Name Type Description Scope
callable types.GeneratorType The wrapped Python generator object that will be iterated. This is a param.ClassSelector parameter that is constant (immutable after initialization) and must be of type types.GeneratorType. instance

Dependencies

  • param
  • types
  • inspect
  • numpy
  • itertools
  • functools
  • collections
  • contextlib
  • numbers

Required Imports

import types
import param
from inspect import FullArgSpec

Usage Example

import types
import param
from inspect import FullArgSpec

# Assuming Callable base class is available
# Create a simple generator function
def my_generator():
    for i in range(5):
        yield i * 2

# Create a generator object
gen_obj = my_generator()

# Wrap it in the Generator class
wrapped_gen = Generator(callable=gen_obj, name='my_wrapped_generator')

# Use the wrapped generator
try:
    value1 = wrapped_gen()  # Returns 0
    value2 = wrapped_gen()  # Returns 2
    value3 = wrapped_gen()  # Returns 4
    # Continue calling until StopIteration
    while True:
        result = wrapped_gen()
        print(result)
except StopIteration:
    print('Generator exhausted')

# Check argspec
print(wrapped_gen.argspec)  # Shows empty argument specification

Best Practices

  • Always wrap a valid generator object (types.GeneratorType) when instantiating this class
  • The callable parameter is constant and cannot be changed after initialization
  • Handle StopIteration exceptions when calling the Generator instance to detect when the generator is exhausted
  • Be aware that generators are stateful - each call advances the generator and cannot be reset
  • The class does not memoize results, so each call produces a new value from the generator
  • Exceptions raised by the generator (other than StopIteration) will be logged with a warning before being re-raised
  • The Generator instance takes no arguments when called - it always calls next() on the wrapped generator
  • Use the argspec property to verify that the Generator accepts no arguments programmatically
  • Since generators maintain state, create a new Generator instance if you need to restart iteration
  • The name parameter (inherited from Callable/param) should be set for better error messages

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function callable_name 46.0% similar

    Extracts and returns a meaningful string name from various types of callable objects including functions, methods, classes, generators, and partial functions.

    From: /tf/active/vicechatdev/patches/util.py
  • class Callable 43.9% similar

    Callable is a wrapper class for callback functions used with DynamicMaps, providing memoization, stream management, and input/output tracking capabilities.

    From: /tf/active/vicechatdev/patches/spaces.py
  • function unique_iterator 43.2% similar

    A generator function that yields unique elements from an input sequence in order of first appearance, filtering out duplicates.

    From: /tf/active/vicechatdev/patches/util.py
  • function get_pdf_generator 42.9% similar

    Factory function that creates and initializes a PDFGenerator instance with registered fonts and optional custom style initialization, using a non-standard instantiation pattern to bypass __init__.

    From: /tf/active/vicechatdev/CDocs/utils/pdf_utils.py
  • class ExcelGenerator 41.8% similar

    Generates structured Excel files from extracted invoice data.

    From: /tf/active/vicechatdev/invoice_extraction/core/excel_generator.py
← Back to Browse