class Generator
Generator is a specialized Callable wrapper class that wraps Python generator objects, providing controlled iteration with no arguments and no memoization.
/tf/active/vicechatdev/patches/spaces.py
606 - 628
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
paramtypesinspectnumpyitertoolsfunctoolscollectionscontextlibnumbers
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function callable_name 46.0% similar
-
class Callable 43.9% similar
-
function unique_iterator 43.2% similar
-
function get_pdf_generator 42.9% similar
-
class ExcelGenerator 41.8% similar