<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _length_scalar_handler(scalar_factory, ion_type, length, ctx):
 """Handles scalars, ``scalar_factory`` is a function that returns a value or thunk."""

    _, self = yield
    if length == 0:
        data = b''
    else:
        yield ctx.read_data_transition(length, self)
        data = ctx.queue.read(length)

    scalar = scalar_factory(data)
    event_cls = IonEvent
    if callable(scalar):
        # TODO Wrap the exception to get context position.
        event_cls = IonThunkEvent
    yield ctx.event_transition(event_cls, IonEventType.SCALAR, ion_type, scalar)