signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def binary_writer(imports=None):
return writer_trampoline(_managed_binary_writer_coroutine(imports))<EOL>
Returns a binary writer co-routine. Keyword Args: imports (Optional[Sequence[SymbolTable]]): A list of shared symbol tables to be used by this writer. Yields: DataEvent: serialization events to write out Receives :class:`amazon.ion.core.IonEvent`.
f5015:m4
def partial_transition(data, delegate):
return Transition(DataEvent(WriteEventType.HAS_PENDING, data), delegate)<EOL>
Generates a :class:`Transition` that has an event indicating ``HAS_PENDING``.
f5016:m0
@coroutine<EOL>def writer_trampoline(start):
trans = Transition(None, start)<EOL>while True:<EOL><INDENT>ion_event = (yield trans.event)<EOL>if trans.event is None:<EOL><INDENT>if ion_event is None:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if trans.event.type is WriteEventType.HAS_PENDING and ion_event is not None:<EOL><INDENT>raise TypeError('<STR_LIT>' % (ion_event,))<EOL><DEDENT>if trans.event.type is not WriteEventType.HAS_PENDING and ion_event is None:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if ion_event is not None and ion_event.event_type is IonEventType.INCOMPLETE:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>trans = trans.delegate.send(Transition(ion_event, trans.delegate))<EOL><DEDENT>
Provides the co-routine trampoline for a writer state machine. The given co-routine is a state machine that yields :class:`Transition` and takes a :class:`Transition` with a :class:`amazon.ion.core.IonEvent` and the co-routine itself. Notes: A writer delimits its logical flush points with ``WriteEventType.COMPLETE``, depending on the configuration, a user may need to send an ``IonEventType.STREAM_END`` to force this to occur. Args: start: The writer co-routine to initially delegate to. Yields: DataEvent: the result of serialization. Receives :class:`amazon.ion.core.IonEvent` to serialize into :class:`DataEvent`.
f5016:m5
def _drain(writer, ion_event):
result_event = _WRITE_EVENT_HAS_PENDING_EMPTY<EOL>while result_event.type is WriteEventType.HAS_PENDING:<EOL><INDENT>result_event = writer.send(ion_event)<EOL>ion_event = None<EOL>yield result_event<EOL><DEDENT>
Drain the writer of its pending write events. Args: writer (Coroutine): A writer co-routine. ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer. Yields: DataEvent: Yields each pending data event.
f5016:m6
@coroutine<EOL>def blocking_writer(writer, output):
result_type = None<EOL>while True:<EOL><INDENT>ion_event = (yield result_type)<EOL>for result_event in _drain(writer, ion_event):<EOL><INDENT>output.write(result_event.data)<EOL><DEDENT>result_type = result_event.type<EOL><DEDENT>
Provides an implementation of using the writer co-routine with a file-like object. Args: writer (Coroutine): A writer co-routine. output (BaseIO): The file-like object to pipe events to. Yields: WriteEventType: Yields when no events are pending. Receives :class:`amazon.ion.core.IonEvent` to write to the ``output``.
f5016:m7
def _illegal_character(c, ctx, message='<STR_LIT>'):
container_type = ctx.container.ion_type is None and '<STR_LIT>' or ctx.container.ion_type.name<EOL>value_type = ctx.ion_type is None and '<STR_LIT>' or ctx.ion_type.name<EOL>if c is None:<EOL><INDENT>header = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>c = '<STR_LIT>' if BufferQueue.is_eof(c) else _chr(c)<EOL>header = '<STR_LIT>' % (c,)<EOL><DEDENT>raise IonException('<STR_LIT>'<EOL>% (header, ctx.queue.position, value_type, container_type, message, ctx.value))<EOL>
Raises an IonException upon encountering the given illegal character in the given context. Args: c (int|None): Ordinal of the illegal character. ctx (_HandlerContext): Context in which the illegal character was encountered. message (Optional[str]): Additional information, as necessary.
f5017:m0
def _defaultdict(dct, fallback=_illegal_character):
out = defaultdict(lambda: fallback)<EOL>for k, v in six.iteritems(dct):<EOL><INDENT>out[k] = v<EOL><DEDENT>return out<EOL>
Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed.
f5017:m1
def _merge_mappings(*args):
dct = {}<EOL>for arg in args:<EOL><INDENT>if isinstance(arg, dict):<EOL><INDENT>merge = arg<EOL><DEDENT>else:<EOL><INDENT>assert isinstance(arg, tuple)<EOL>keys, value = arg<EOL>merge = dict(zip(keys, [value]*len(keys)))<EOL><DEDENT>dct.update(merge)<EOL><DEDENT>return dct<EOL>
Merges a sequence of dictionaries and/or tuples into a single dictionary. If a given argument is a tuple, it must have two elements, the first of which is a sequence of keys and the second of which is a single value, which will be mapped to from each of the keys in the sequence.
f5017:m2
def _seq(s):
return tuple(six.iterbytes(s))<EOL>
Converts bytes to a sequence of integer code points.
f5017:m3
def _is_escaped(c):
try:<EOL><INDENT>return c.is_escaped<EOL><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>
Queries whether a character ordinal or code point was part of an escape sequence.
f5017:m5
def _as_symbol(value, is_symbol_value=True):
try:<EOL><INDENT>return value.as_symbol()<EOL><DEDENT>except AttributeError:<EOL><INDENT>assert isinstance(value, SymbolToken)<EOL><DEDENT>if not is_symbol_value:<EOL><INDENT>try:<EOL><INDENT>return value.regular_token()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return value<EOL>
Converts the input to a :class:`SymbolToken` suitable for being emitted as part of a :class:`IonEvent`. If the input has an `as_symbol` method (e.g. :class:`CodePointArray`), it will be converted using that method. Otherwise, it must already be a `SymbolToken`. In this case, there is nothing to do unless the input token is not a symbol value and it is an :class:`_IVMToken`. This requires the `_IVMToken` to be converted to a regular `SymbolToken`.
f5017:m6
@coroutine<EOL>def _number_negative_start_handler(c, ctx):
assert c == _MINUS<EOL>assert len(ctx.value) == <NUM_LIT:0><EOL>ctx.set_ion_type(IonType.INT)<EOL>ctx.value.append(c)<EOL>c, _ = yield<EOL>yield ctx.immediate_transition(_NEGATIVE_TABLE[c](c, ctx))<EOL>
Handles numeric values that start with a negative sign. Branches to delegate co-routines according to _NEGATIVE_TABLE.
f5017:m11
@coroutine<EOL>def _number_zero_start_handler(c, ctx):
assert c == _ZERO<EOL>assert len(ctx.value) == <NUM_LIT:0> or (len(ctx.value) == <NUM_LIT:1> and ctx.value[<NUM_LIT:0>] == _MINUS)<EOL>ctx.set_ion_type(IonType.INT)<EOL>ctx.value.append(c)<EOL>c, _ = yield<EOL>if _ends_value(c):<EOL><INDENT>trans = ctx.event_transition(IonThunkEvent, IonEventType.SCALAR, ctx.ion_type, _parse_decimal_int(ctx.value))<EOL>if c == _SLASH:<EOL><INDENT>trans = ctx.immediate_transition(_number_slash_end_handler(c, ctx, trans))<EOL><DEDENT>yield trans<EOL><DEDENT>yield ctx.immediate_transition(_ZERO_START_TABLE[c](c, ctx))<EOL>
Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to _ZERO_START_TABLE.
f5017:m12
@coroutine<EOL>def _number_or_timestamp_handler(c, ctx):
assert c in _DIGITS<EOL>ctx.set_ion_type(IonType.INT) <EOL>val = ctx.value<EOL>val.append(c)<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>while True:<EOL><INDENT>if _ends_value(c):<EOL><INDENT>trans = ctx.event_transition(IonThunkEvent, IonEventType.SCALAR,<EOL>ctx.ion_type, _parse_decimal_int(ctx.value))<EOL>if c == _SLASH:<EOL><INDENT>trans = ctx.immediate_transition(_number_slash_end_handler(c, ctx, trans))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if c not in _DIGITS:<EOL><INDENT>trans = ctx.immediate_transition(_NUMBER_OR_TIMESTAMP_TABLE[c](c, ctx))<EOL><DEDENT>else:<EOL><INDENT>val.append(c)<EOL><DEDENT><DEDENT>c, _ = yield trans<EOL><DEDENT>
Handles numeric values that start with digits 1-9. May terminate a value, in which case that value is an int. If it does not terminate a value, it branches to delegate co-routines according to _NUMBER_OR_TIMESTAMP_TABLE.
f5017:m13
@coroutine<EOL>def _number_slash_end_handler(c, ctx, event):
assert c == _SLASH<EOL>c, self = yield<EOL>next_ctx = ctx.derive_child_context(ctx.whence)<EOL>comment = _comment_handler(_SLASH, next_ctx, next_ctx.whence)<EOL>comment.send((c, comment))<EOL>yield _CompositeTransition(event, ctx, comment, next_ctx, initialize_handler=False)<EOL>
Handles numeric values that end in a forward slash. This is only legal if the slash begins a comment; thus, this co-routine either results in an error being raised or an event being yielded.
f5017:m14
def _numeric_handler_factory(charset, transition, assertion, illegal_before_underscore, parse_func,<EOL>illegal_at_end=(None,), ion_type=None, append_first_if_not=None, first_char=None):
@coroutine<EOL>def numeric_handler(c, ctx):<EOL><INDENT>assert assertion(c, ctx)<EOL>if ion_type is not None:<EOL><INDENT>ctx.set_ion_type(ion_type)<EOL><DEDENT>val = ctx.value<EOL>if c != append_first_if_not:<EOL><INDENT>first = c if first_char is None else first_char<EOL>val.append(first)<EOL><DEDENT>prev = c<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>while True:<EOL><INDENT>if _ends_value(c):<EOL><INDENT>if prev == _UNDERSCORE or prev in illegal_at_end:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % (_chr(prev),))<EOL><DEDENT>trans = ctx.event_transition(IonThunkEvent, IonEventType.SCALAR, ctx.ion_type, parse_func(ctx.value))<EOL>if c == _SLASH:<EOL><INDENT>trans = ctx.immediate_transition(_number_slash_end_handler(c, ctx, trans))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if c == _UNDERSCORE:<EOL><INDENT>if prev == _UNDERSCORE or prev in illegal_before_underscore:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % (_chr(prev),))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if c not in charset:<EOL><INDENT>trans = transition(prev, c, ctx, trans)<EOL><DEDENT>else:<EOL><INDENT>val.append(c)<EOL><DEDENT><DEDENT><DEDENT>prev = c<EOL>c, _ = yield trans<EOL><DEDENT><DEDENT>return numeric_handler<EOL>
Generates a handler co-routine which tokenizes a numeric component (a token or sub-token). Args: charset (sequence): Set of ordinals of legal characters for this numeric component. transition (callable): Called upon termination of this component (i.e. when a character not in ``charset`` is found). Accepts the previous character ordinal, the current character ordinal, the current context, and the previous transition. Returns a Transition if the component ends legally; otherwise, raises an error. assertion (callable): Accepts the first character's ordinal and the current context. Returns True if this is a legal start to the component. illegal_before_underscore (sequence): Set of ordinals of illegal characters to precede an underscore for this component. parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a thunk that lazily parses the token. illegal_at_end (Optional[sequence]): Set of ordinals of characters that may not legally end the value. ion_type (Optional[IonType]): The type of the value if it were to end on this component. append_first_if_not (Optional[int]): The ordinal of a character that should not be appended to the token if it occurs first in this component (e.g. an underscore in many cases). first_char (Optional[int]): The ordinal of the character that should be appended instead of the character that occurs first in this component. This is useful for preparing the token for parsing in the case where a particular character is peculiar to the Ion format (e.g. 'd' to denote the exponent of a decimal value should be replaced with 'e' for compatibility with python's Decimal type).
f5017:m15
def _exponent_handler_factory(ion_type, exp_chars, parse_func, first_char=None):
def transition(prev, c, ctx, trans):<EOL><INDENT>if c in _SIGN and prev in exp_chars:<EOL><INDENT>ctx.value.append(c)<EOL><DEDENT>else:<EOL><INDENT>_illegal_character(c, ctx)<EOL><DEDENT>return trans<EOL><DEDENT>illegal = exp_chars + _SIGN<EOL>return _numeric_handler_factory(_DIGITS, transition, lambda c, ctx: c in exp_chars, illegal, parse_func,<EOL>illegal_at_end=illegal, ion_type=ion_type, first_char=first_char)<EOL>
Generates a handler co-routine which tokenizes an numeric exponent. Args: ion_type (IonType): The type of the value with this exponent. exp_chars (sequence): The set of ordinals of the legal exponent characters for this component. parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a thunk that lazily parses the token. first_char (Optional[int]): The ordinal of the character that should be appended instead of the character that occurs first in this component. This is useful for preparing the token for parsing in the case where a particular character is peculiar to the Ion format (e.g. 'd' to denote the exponent of a decimal value should be replaced with 'e' for compatibility with python's Decimal type).
f5017:m16
def _coefficient_handler_factory(trans_table, parse_func, assertion=lambda c, ctx: True,<EOL>ion_type=None, append_first_if_not=None):
def transition(prev, c, ctx, trans):<EOL><INDENT>if prev == _UNDERSCORE:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % (_chr(c),))<EOL><DEDENT>return ctx.immediate_transition(trans_table[c](c, ctx))<EOL><DEDENT>return _numeric_handler_factory(_DIGITS, transition, assertion, (_DOT,), parse_func,<EOL>ion_type=ion_type, append_first_if_not=append_first_if_not)<EOL>
Generates a handler co-routine which tokenizes a numeric coefficient. Args: trans_table (dict): lookup table for the handler for the next component of this numeric token, given the ordinal of the first character in that component. parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a thunk that lazily parses the token. assertion (callable): Accepts the first character's ordinal and the current context. Returns True if this is a legal start to the component. ion_type (Optional[IonType]): The type of the value if it were to end on this coefficient. append_first_if_not (Optional[int]): The ordinal of a character that should not be appended to the token if it occurs first in this component (e.g. an underscore in many cases).
f5017:m17
def _radix_int_handler_factory(radix_indicators, charset, parse_func):
def assertion(c, ctx):<EOL><INDENT>return c in radix_indicators and((len(ctx.value) == <NUM_LIT:1> and ctx.value[<NUM_LIT:0>] == _ZERO) or<EOL>(len(ctx.value) == <NUM_LIT:2> and ctx.value[<NUM_LIT:0>] == _MINUS and ctx.value[<NUM_LIT:1>] == _ZERO)) andctx.ion_type == IonType.INT<EOL><DEDENT>return _numeric_handler_factory(charset, lambda prev, c, ctx, trans: _illegal_character(c, ctx),<EOL>assertion, radix_indicators, parse_func, illegal_at_end=radix_indicators)<EOL>
Generates a handler co-routine which tokenizes a integer of a particular radix. Args: radix_indicators (sequence): The set of ordinals of characters that indicate the radix of this int. charset (sequence): Set of ordinals of legal characters for this radix. parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a thunk that lazily parses the token.
f5017:m18
@coroutine<EOL>def _timestamp_zero_start_handler(c, ctx):
val = ctx.value<EOL>ctx.set_ion_type(IonType.TIMESTAMP)<EOL>if val[<NUM_LIT:0>] == _MINUS:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>')<EOL><DEDENT>val.append(c)<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>while True:<EOL><INDENT>if c in _TIMESTAMP_YEAR_DELIMITERS:<EOL><INDENT>trans = ctx.immediate_transition(_timestamp_handler(c, ctx))<EOL><DEDENT>elif c in _DIGITS:<EOL><INDENT>val.append(c)<EOL><DEDENT>else:<EOL><INDENT>_illegal_character(c, ctx)<EOL><DEDENT>c, _ = yield trans<EOL><DEDENT>
Handles numeric values that start with a zero followed by another digit. This is either a timestamp or an error.
f5017:m19
def _parse_timestamp(tokens):
def parse():<EOL><INDENT>precision = TimestampPrecision.YEAR<EOL>off_hour = tokens[_TimestampState.OFF_HOUR]<EOL>off_minutes = tokens[_TimestampState.OFF_MINUTE]<EOL>microsecond = None<EOL>fraction_digits = None<EOL>if off_hour is not None:<EOL><INDENT>assert off_minutes is not None<EOL>off_sign = -<NUM_LIT:1> if _MINUS in off_hour else <NUM_LIT:1><EOL>off_hour = int(off_hour)<EOL>off_minutes = int(off_minutes) * off_sign<EOL>if off_sign == -<NUM_LIT:1> and off_hour == <NUM_LIT:0> and off_minutes == <NUM_LIT:0>:<EOL><INDENT>off_hour = None<EOL>off_minutes = None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>assert off_minutes is None<EOL><DEDENT>year = tokens[_TimestampState.YEAR]<EOL>assert year is not None<EOL>year = int(year)<EOL>month = tokens[_TimestampState.MONTH]<EOL>if month is None:<EOL><INDENT>month = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>month = int(month)<EOL>precision = TimestampPrecision.MONTH<EOL><DEDENT>day = tokens[_TimestampState.DAY]<EOL>if day is None:<EOL><INDENT>day = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>day = int(day)<EOL>precision = TimestampPrecision.DAY<EOL><DEDENT>hour = tokens[_TimestampState.HOUR]<EOL>minute = tokens[_TimestampState.MINUTE]<EOL>if hour is None:<EOL><INDENT>assert minute is None<EOL>hour = <NUM_LIT:0><EOL>minute = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>assert minute is not None<EOL>hour = int(hour)<EOL>minute = int(minute)<EOL>precision = TimestampPrecision.MINUTE<EOL><DEDENT>second = tokens[_TimestampState.SECOND]<EOL>if second is None:<EOL><INDENT>second = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>second = int(second)<EOL>precision = TimestampPrecision.SECOND<EOL>fraction = tokens[_TimestampState.FRACTIONAL]<EOL>if fraction is not None:<EOL><INDENT>fraction_digits = len(fraction)<EOL>if fraction_digits > MICROSECOND_PRECISION:<EOL><INDENT>for digit in fraction[MICROSECOND_PRECISION:]:<EOL><INDENT>if digit != _ZERO:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% (fraction,))<EOL><DEDENT><DEDENT>fraction_digits = MICROSECOND_PRECISION<EOL>fraction = fraction[<NUM_LIT:0>:MICROSECOND_PRECISION]<EOL><DEDENT>else:<EOL><INDENT>fraction.extend(_ZEROS[MICROSECOND_PRECISION - fraction_digits])<EOL><DEDENT>microsecond = int(fraction)<EOL><DEDENT><DEDENT>return timestamp(<EOL>year, month, day,<EOL>hour, minute, second, microsecond,<EOL>off_hour, off_minutes,<EOL>precision=precision, fractional_precision=fraction_digits<EOL>)<EOL><DEDENT>return parse<EOL>
Parses each token in the given `_TimestampTokens` and marshals the numeric components into a `Timestamp`.
f5017:m20
@coroutine<EOL>def _timestamp_handler(c, ctx):
assert c in _TIMESTAMP_YEAR_DELIMITERS<EOL>ctx.set_ion_type(IonType.TIMESTAMP)<EOL>if len(ctx.value) != <NUM_LIT:4>:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % (len(ctx.value),))<EOL><DEDENT>prev = c<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>state = _TimestampState.YEAR<EOL>nxt = _DIGITS<EOL>tokens = _TimestampTokens(ctx.value)<EOL>val = None<EOL>can_terminate = False<EOL>if prev == _T:<EOL><INDENT>nxt += _VALUE_TERMINATORS<EOL>can_terminate = True<EOL><DEDENT>while True:<EOL><INDENT>is_eof = can_terminate and BufferQueue.is_eof(c)<EOL>if c not in nxt and not is_eof:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % ([_chr(x) for x in nxt], state))<EOL><DEDENT>if c in _VALUE_TERMINATORS or is_eof:<EOL><INDENT>if not can_terminate:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>')<EOL><DEDENT>trans = ctx.event_transition(IonThunkEvent, IonEventType.SCALAR, ctx.ion_type, _parse_timestamp(tokens))<EOL>if c == _SLASH:<EOL><INDENT>trans = ctx.immediate_transition(_number_slash_end_handler(c, ctx, trans))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>can_terminate = False<EOL>if c == _Z:<EOL><INDENT>tokens.transition(_TimestampState.OFF_HOUR).append(_ZERO)<EOL>tokens.transition(_TimestampState.OFF_MINUTE).append(_ZERO)<EOL>nxt = _VALUE_TERMINATORS<EOL>can_terminate = True<EOL><DEDENT>elif c == _T:<EOL><INDENT>nxt = _VALUE_TERMINATORS + _DIGITS<EOL>can_terminate = True<EOL><DEDENT>elif c in _TIMESTAMP_DELIMITERS:<EOL><INDENT>nxt = _DIGITS<EOL><DEDENT>elif c in _DIGITS:<EOL><INDENT>if prev == _PLUS or (state > _TimestampState.MONTH and prev == _HYPHEN):<EOL><INDENT>state = _TimestampState.OFF_HOUR<EOL>val = tokens.transition(state)<EOL>if prev == _HYPHEN:<EOL><INDENT>val.append(prev)<EOL><DEDENT><DEDENT>elif prev in (_TIMESTAMP_DELIMITERS + (_T,)):<EOL><INDENT>state = _TimestampState[state + <NUM_LIT:1>]<EOL>val = tokens.transition(state)<EOL>if state == _TimestampState.FRACTIONAL:<EOL><INDENT>nxt = _DIGITS + _TIMESTAMP_OFFSET_INDICATORS<EOL><DEDENT><DEDENT>elif prev in _DIGITS:<EOL><INDENT>if state == _TimestampState.MONTH:<EOL><INDENT>nxt = _TIMESTAMP_YEAR_DELIMITERS<EOL><DEDENT>elif state == _TimestampState.DAY:<EOL><INDENT>nxt = (_T,) + _VALUE_TERMINATORS<EOL>can_terminate = True<EOL><DEDENT>elif state == _TimestampState.HOUR:<EOL><INDENT>nxt = (_COLON,)<EOL><DEDENT>elif state == _TimestampState.MINUTE:<EOL><INDENT>nxt = _TIMESTAMP_OFFSET_INDICATORS + (_COLON,)<EOL><DEDENT>elif state == _TimestampState.SECOND:<EOL><INDENT>nxt = _TIMESTAMP_OFFSET_INDICATORS + (_DOT,)<EOL><DEDENT>elif state == _TimestampState.FRACTIONAL:<EOL><INDENT>nxt = _DIGITS + _TIMESTAMP_OFFSET_INDICATORS<EOL><DEDENT>elif state == _TimestampState.OFF_HOUR:<EOL><INDENT>nxt = (_COLON,)<EOL><DEDENT>elif state == _TimestampState.OFF_MINUTE:<EOL><INDENT>nxt = _VALUE_TERMINATORS<EOL>can_terminate = True<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % (state,))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % (_chr(prev), state))<EOL><DEDENT>val.append(c)<EOL><DEDENT><DEDENT>prev = c<EOL>c, _ = yield trans<EOL><DEDENT>
Handles timestamp values. Entered after the year component has been completed; tokenizes the remaining components.
f5017:m21
@coroutine<EOL>def _comment_handler(c, ctx, whence):
assert c == _SLASH<EOL>c, self = yield<EOL>if c == _SLASH:<EOL><INDENT>ctx.set_line_comment()<EOL>block_comment = False<EOL><DEDENT>elif c == _ASTERISK:<EOL><INDENT>if ctx.line_comment:<EOL><INDENT>ctx.set_line_comment(False)<EOL><DEDENT>block_comment = True<EOL><DEDENT>else:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % (_chr(c),))<EOL><DEDENT>done = False<EOL>prev = None<EOL>trans = ctx.immediate_transition(self)<EOL>while not done:<EOL><INDENT>c, _ = yield trans<EOL>if block_comment:<EOL><INDENT>if prev == _ASTERISK and c == _SLASH:<EOL><INDENT>done = True<EOL><DEDENT>prev = c<EOL><DEDENT>else:<EOL><INDENT>if c in _NEWLINES or BufferQueue.is_eof(c):<EOL><INDENT>done = True<EOL><DEDENT><DEDENT><DEDENT>yield ctx.set_self_delimiting(True).immediate_transition(whence)<EOL>
Handles comments. Upon completion of the comment, immediately transitions back to `whence`.
f5017:m22
@coroutine<EOL>def _sexp_slash_handler(c, ctx, whence=None, pending_event=None):
assert c == _SLASH<EOL>if whence is None:<EOL><INDENT>whence = ctx.whence<EOL><DEDENT>c, self = yield<EOL>ctx.queue.unread(c)<EOL>if c == _ASTERISK or c == _SLASH:<EOL><INDENT>yield ctx.immediate_transition(_comment_handler(_SLASH, ctx, whence))<EOL><DEDENT>else:<EOL><INDENT>if pending_event is not None:<EOL><INDENT>assert pending_event.event is not None<EOL>yield _CompositeTransition(pending_event, ctx, partial(_operator_symbol_handler, _SLASH))<EOL><DEDENT>yield ctx.immediate_transition(_operator_symbol_handler(_SLASH, ctx))<EOL><DEDENT>
Handles the special case of a forward-slash within an s-expression. This is either an operator or a comment.
f5017:m23
@coroutine<EOL>def _long_string_handler(c, ctx, is_field_name=False):
assert c == _SINGLE_QUOTE<EOL>is_clob = ctx.ion_type is IonType.CLOB<EOL>max_char = _MAX_CLOB_CHAR if is_clob else _MAX_TEXT_CHAR<EOL>assert not (is_clob and is_field_name)<EOL>if not is_clob and not is_field_name:<EOL><INDENT>ctx.set_ion_type(IonType.STRING)<EOL><DEDENT>assert not ctx.value<EOL>ctx.set_unicode(quoted_text=True)<EOL>val = ctx.value<EOL>if is_field_name:<EOL><INDENT>assert not val<EOL>ctx.set_pending_symbol()<EOL>val = ctx.pending_symbol<EOL><DEDENT>quotes = <NUM_LIT:0><EOL>in_data = True<EOL>c, self = yield<EOL>here = ctx.immediate_transition(self)<EOL>trans = here<EOL>while True:<EOL><INDENT>if c == _SINGLE_QUOTE and not _is_escaped(c):<EOL><INDENT>quotes += <NUM_LIT:1><EOL>if quotes == <NUM_LIT:3>:<EOL><INDENT>in_data = not in_data<EOL>ctx.set_quoted_text(in_data)<EOL>quotes = <NUM_LIT:0><EOL><DEDENT><DEDENT>else:<EOL><INDENT>if in_data:<EOL><INDENT>_validate_long_string_text(c, ctx, max_char)<EOL>val.extend(_SINGLE_QUOTES[quotes])<EOL>if not _is_escaped_newline(c):<EOL><INDENT>val.append(c)<EOL><DEDENT>quotes = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>if quotes > <NUM_LIT:0>:<EOL><INDENT>assert quotes < <NUM_LIT:3><EOL>if is_field_name or is_clob:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % (val,))<EOL><DEDENT>else:<EOL><INDENT>if ctx.container.is_delimited:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>'<EOL>% (_chr(ctx.container.delimiter[<NUM_LIT:0>]),))<EOL><DEDENT>trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, ctx.ion_type, ctx.value.as_text())<EOL>if quotes == <NUM_LIT:1>:<EOL><INDENT>if BufferQueue.is_eof(c):<EOL><INDENT>_illegal_character(c, ctx, "<STR_LIT>")<EOL><DEDENT>ctx.queue.unread(c)<EOL>ctx.set_quoted_text(True)<EOL>c, _ = yield ctx.immediate_transition(self)<EOL>trans = _CompositeTransition(<EOL>trans,<EOL>ctx,<EOL>partial(_quoted_symbol_handler, c, is_field_name=False),<EOL>)<EOL><DEDENT>else: <EOL><INDENT>trans = _CompositeTransition(trans, ctx, None, ctx.set_empty_symbol())<EOL><DEDENT><DEDENT><DEDENT>elif c not in _WHITESPACE:<EOL><INDENT>if is_clob:<EOL><INDENT>trans = ctx.immediate_transition(_clob_end_handler(c, ctx))<EOL><DEDENT>elif c == _SLASH:<EOL><INDENT>if ctx.container.ion_type is IonType.SEXP:<EOL><INDENT>pending = ctx.event_transition(IonEvent, IonEventType.SCALAR,<EOL>ctx.ion_type, ctx.value.as_text())<EOL>trans = ctx.immediate_transition(_sexp_slash_handler(c, ctx, self, pending))<EOL><DEDENT>else:<EOL><INDENT>trans = ctx.immediate_transition(_comment_handler(c, ctx, self))<EOL><DEDENT><DEDENT>elif is_field_name:<EOL><INDENT>if c != _COLON:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % (val,))<EOL><DEDENT>trans = ctx.immediate_transition(ctx.whence)<EOL><DEDENT>else:<EOL><INDENT>trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, ctx.ion_type, ctx.value.as_text())<EOL><DEDENT><DEDENT><DEDENT><DEDENT>c, _ = yield trans<EOL>ctx.set_self_delimiting(False) <EOL>trans = here<EOL><DEDENT>
Handles triple-quoted strings. Remains active until a value other than a long string is encountered.
f5017:m26
@coroutine<EOL>def _typed_null_handler(c, ctx):
assert c == _DOT<EOL>c, self = yield<EOL>nxt = _NULL_STARTS<EOL>i = <NUM_LIT:0><EOL>length = None<EOL>done = False<EOL>trans = ctx.immediate_transition(self)<EOL>while True:<EOL><INDENT>if done:<EOL><INDENT>if _ends_value(c) or (ctx.container.ion_type is IonType.SEXP and c in _OPERATORS):<EOL><INDENT>trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, nxt.ion_type, None)<EOL><DEDENT>else:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>')<EOL><DEDENT><DEDENT>elif length is None:<EOL><INDENT>if c not in nxt:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>')<EOL><DEDENT>nxt = nxt[c]<EOL>if isinstance(nxt, _NullSequence):<EOL><INDENT>length = len(nxt.sequence)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if c != nxt[i]:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>')<EOL><DEDENT>i += <NUM_LIT:1><EOL>done = i == length<EOL><DEDENT>c, _ = yield trans<EOL><DEDENT>
Handles typed null values. Entered once `null.` has been found.
f5017:m27
@coroutine<EOL>def _symbol_or_keyword_handler(c, ctx, is_field_name=False):
in_sexp = ctx.container.ion_type is IonType.SEXP<EOL>if c not in _IDENTIFIER_STARTS:<EOL><INDENT>if in_sexp and c in _OPERATORS:<EOL><INDENT>c_next, _ = yield<EOL>ctx.queue.unread(c_next)<EOL>yield ctx.immediate_transition(_operator_symbol_handler(c, ctx))<EOL><DEDENT>_illegal_character(c, ctx)<EOL><DEDENT>assert not ctx.value<EOL>ctx.set_unicode().set_ion_type(IonType.SYMBOL)<EOL>val = ctx.value<EOL>val.append(c)<EOL>maybe_null = c == _N_LOWER<EOL>maybe_nan = maybe_null<EOL>maybe_true = c == _T_LOWER<EOL>maybe_false = c == _F_LOWER<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>keyword_trans = None<EOL>match_index = <NUM_LIT:0><EOL>while True:<EOL><INDENT>def check_keyword(name, keyword_sequence, ion_type, value, match_transition=lambda: None):<EOL><INDENT>maybe_keyword = True<EOL>transition = None<EOL>if match_index < len(keyword_sequence):<EOL><INDENT>maybe_keyword = c == keyword_sequence[match_index]<EOL><DEDENT>else:<EOL><INDENT>transition = match_transition()<EOL>if transition is not None:<EOL><INDENT>pass<EOL><DEDENT>elif _ends_value(c):<EOL><INDENT>if is_field_name:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>' % (name,))<EOL><DEDENT>transition = ctx.event_transition(IonEvent, IonEventType.SCALAR, ion_type, value)<EOL><DEDENT>elif c == _COLON:<EOL><INDENT>message = '<STR_LIT>'<EOL>if is_field_name:<EOL><INDENT>message = '<STR_LIT>' % (name,)<EOL><DEDENT>_illegal_character(c, ctx, message)<EOL><DEDENT>elif in_sexp and c in _OPERATORS:<EOL><INDENT>transition = ctx.event_transition(IonEvent, IonEventType.SCALAR, ion_type, value)<EOL><DEDENT>else:<EOL><INDENT>maybe_keyword = False<EOL><DEDENT><DEDENT>return maybe_keyword, transition<EOL><DEDENT>if maybe_null:<EOL><INDENT>def check_null_dot():<EOL><INDENT>transition = None<EOL>found = c == _DOT<EOL>if found:<EOL><INDENT>if is_field_name:<EOL><INDENT>_illegal_character(c, ctx, "<STR_LIT>")<EOL><DEDENT>transition = ctx.immediate_transition(_typed_null_handler(c, ctx))<EOL><DEDENT>return transition<EOL><DEDENT>maybe_null, keyword_trans = check_keyword('<STR_LIT:null>', _NULL_SUFFIX.sequence,<EOL>IonType.NULL, None, check_null_dot)<EOL><DEDENT>if maybe_nan:<EOL><INDENT>maybe_nan, keyword_trans = check_keyword('<STR_LIT>', _NAN_SUFFIX, IonType.FLOAT, _NAN)<EOL><DEDENT>elif maybe_true:<EOL><INDENT>maybe_true, keyword_trans = check_keyword('<STR_LIT:true>', _TRUE_SUFFIX, IonType.BOOL, True)<EOL><DEDENT>elif maybe_false:<EOL><INDENT>maybe_false, keyword_trans = check_keyword('<STR_LIT:false>', _FALSE_SUFFIX, IonType.BOOL, False)<EOL><DEDENT>if maybe_null or maybe_nan or maybe_true or maybe_false:<EOL><INDENT>if keyword_trans is not None:<EOL><INDENT>trans = keyword_trans<EOL><DEDENT>else:<EOL><INDENT>val.append(c)<EOL>match_index += <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>if c in _SYMBOL_TOKEN_TERMINATORS:<EOL><INDENT>ctx.set_pending_symbol(val)<EOL>trans = ctx.immediate_transition(ctx.whence)<EOL><DEDENT>elif _ends_value(c) or (in_sexp and c in _OPERATORS):<EOL><INDENT>trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, val.as_symbol())<EOL><DEDENT>else:<EOL><INDENT>trans = ctx.immediate_transition(_unquoted_symbol_handler(c, ctx, is_field_name=is_field_name))<EOL><DEDENT><DEDENT>c, _ = yield trans<EOL><DEDENT>
Handles the start of an unquoted text token. This may be an operator (if in an s-expression), an identifier symbol, or a keyword.
f5017:m28
def _inf_or_operator_handler_factory(c_start, is_delegate=True):
@coroutine<EOL>def inf_or_operator_handler(c, ctx):<EOL><INDENT>next_ctx = None<EOL>if not is_delegate:<EOL><INDENT>ctx.value.append(c_start)<EOL>c, self = yield<EOL><DEDENT>else:<EOL><INDENT>assert ctx.value[<NUM_LIT:0>] == c_start<EOL>assert c not in _DIGITS<EOL>ctx.queue.unread(c)<EOL>next_ctx = ctx<EOL>_, self = yield<EOL>assert c == _<EOL><DEDENT>maybe_inf = True<EOL>ctx.set_ion_type(IonType.FLOAT)<EOL>match_index = <NUM_LIT:0><EOL>trans = ctx.immediate_transition(self)<EOL>while True:<EOL><INDENT>if maybe_inf:<EOL><INDENT>if match_index < len(_INF_SUFFIX):<EOL><INDENT>maybe_inf = c == _INF_SUFFIX[match_index]<EOL><DEDENT>else:<EOL><INDENT>if _ends_value(c) or (ctx.container.ion_type is IonType.SEXP and c in _OPERATORS):<EOL><INDENT>yield ctx.event_transition(<EOL>IonEvent, IonEventType.SCALAR, IonType.FLOAT, c_start == _MINUS and _NEG_INF or _POS_INF<EOL>)<EOL><DEDENT>else:<EOL><INDENT>maybe_inf = False<EOL><DEDENT><DEDENT><DEDENT>if maybe_inf:<EOL><INDENT>match_index += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>ctx.set_unicode()<EOL>if match_index > <NUM_LIT:0>:<EOL><INDENT>next_ctx = ctx.derive_child_context(ctx.whence)<EOL>for ch in _INF_SUFFIX[<NUM_LIT:0>:match_index]:<EOL><INDENT>next_ctx.value.append(ch)<EOL><DEDENT><DEDENT>break<EOL><DEDENT>c, self = yield trans<EOL><DEDENT>if ctx.container is not _C_SEXP:<EOL><INDENT>_illegal_character(c, next_ctx is None and ctx or next_ctx,<EOL>'<STR_LIT>' % (_chr(c_start),))<EOL><DEDENT>if match_index == <NUM_LIT:0>:<EOL><INDENT>if c in _OPERATORS:<EOL><INDENT>yield ctx.immediate_transition(_operator_symbol_handler(c, ctx))<EOL><DEDENT>yield ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol())<EOL><DEDENT>yield _CompositeTransition(<EOL>ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol()),<EOL>ctx,<EOL>partial(_unquoted_symbol_handler, c),<EOL>next_ctx<EOL>)<EOL><DEDENT>return inf_or_operator_handler<EOL>
Generates handler co-routines for values that may be `+inf` or `-inf`. Args: c_start (int): The ordinal of the character that starts this token (either `+` or `-`). is_delegate (bool): True if a different handler began processing this token; otherwise, False. This will only be true for `-inf`, because it is not the only value that can start with `-`; `+inf` is the only value (outside of a s-expression) that can start with `+`.
f5017:m29
@coroutine<EOL>def _operator_symbol_handler(c, ctx):
assert c in _OPERATORS<EOL>ctx.set_unicode()<EOL>val = ctx.value<EOL>val.append(c)<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>while c in _OPERATORS:<EOL><INDENT>val.append(c)<EOL>c, _ = yield trans<EOL><DEDENT>yield ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, val.as_symbol())<EOL>
Handles operator symbol values within s-expressions.
f5017:m30
def _symbol_token_end(c, ctx, is_field_name, value=None):
if value is None:<EOL><INDENT>value = ctx.value<EOL><DEDENT>if is_field_name or c in _SYMBOL_TOKEN_TERMINATORS or ctx.quoted_text:<EOL><INDENT>ctx.set_self_delimiting(ctx.quoted_text).set_pending_symbol(value).set_quoted_text(False)<EOL>trans = ctx.immediate_transition(ctx.whence)<EOL><DEDENT>else:<EOL><INDENT>trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, _as_symbol(value))<EOL><DEDENT>return trans<EOL>
Returns a transition which ends the current symbol token.
f5017:m31
@coroutine<EOL>def _unquoted_symbol_handler(c, ctx, is_field_name=False):
in_sexp = ctx.container.ion_type is IonType.SEXP<EOL>ctx.set_unicode()<EOL>if c not in _IDENTIFIER_CHARACTERS:<EOL><INDENT>if in_sexp and c in _OPERATORS:<EOL><INDENT>c_next, _ = yield<EOL>ctx.queue.unread(c_next)<EOL>assert ctx.value<EOL>yield _CompositeTransition(<EOL>ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, ctx.value.as_symbol()),<EOL>ctx,<EOL>partial(_operator_symbol_handler, c)<EOL>)<EOL><DEDENT>_illegal_character(c, ctx.set_ion_type(IonType.SYMBOL))<EOL><DEDENT>val = ctx.value<EOL>val.append(c)<EOL>prev = c<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>while True:<EOL><INDENT>if c not in _WHITESPACE:<EOL><INDENT>if prev in _WHITESPACE or _ends_value(c) or c == _COLON or (in_sexp and c in _OPERATORS):<EOL><INDENT>break<EOL><DEDENT>if c not in _IDENTIFIER_CHARACTERS:<EOL><INDENT>_illegal_character(c, ctx.set_ion_type(IonType.SYMBOL))<EOL><DEDENT>val.append(c)<EOL><DEDENT>prev = c<EOL>c, _ = yield trans<EOL><DEDENT>yield _symbol_token_end(c, ctx, is_field_name)<EOL>
Handles identifier symbol tokens. If in an s-expression, these may be followed without whitespace by operators.
f5017:m32
@coroutine<EOL>def _symbol_identifier_or_unquoted_symbol_handler(c, ctx, is_field_name=False):
assert c == _DOLLAR_SIGN<EOL>in_sexp = ctx.container.ion_type is IonType.SEXP<EOL>ctx.set_unicode().set_ion_type(IonType.SYMBOL)<EOL>val = ctx.value<EOL>val.append(c)<EOL>prev = c<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>maybe_ivm = ctx.depth == <NUM_LIT:0> and not is_field_name and not ctx.annotations<EOL>complete_ivm = False<EOL>maybe_symbol_identifier = True<EOL>match_index = <NUM_LIT:1><EOL>ivm_post_underscore = False<EOL>while True:<EOL><INDENT>if c not in _WHITESPACE:<EOL><INDENT>if prev in _WHITESPACE or _ends_value(c) or c == _COLON or (in_sexp and c in _OPERATORS):<EOL><INDENT>break<EOL><DEDENT>maybe_symbol_identifier = maybe_symbol_identifier and c in _DIGITS<EOL>if maybe_ivm:<EOL><INDENT>if match_index == len(_IVM_PREFIX):<EOL><INDENT>if c in _DIGITS:<EOL><INDENT>if ivm_post_underscore:<EOL><INDENT>complete_ivm = True<EOL><DEDENT><DEDENT>elif c == _UNDERSCORE and not ivm_post_underscore:<EOL><INDENT>ivm_post_underscore = True<EOL><DEDENT>else:<EOL><INDENT>maybe_ivm = False<EOL>complete_ivm = False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>maybe_ivm = c == _IVM_PREFIX[match_index]<EOL><DEDENT><DEDENT>if maybe_ivm:<EOL><INDENT>if match_index < len(_IVM_PREFIX):<EOL><INDENT>match_index += <NUM_LIT:1><EOL><DEDENT><DEDENT>elif not maybe_symbol_identifier:<EOL><INDENT>yield ctx.immediate_transition(_unquoted_symbol_handler(c, ctx, is_field_name))<EOL><DEDENT>val.append(c)<EOL><DEDENT>elif match_index < len(_IVM_PREFIX):<EOL><INDENT>maybe_ivm = False<EOL><DEDENT>prev = c<EOL>c, _ = yield trans<EOL><DEDENT>if len(val) == <NUM_LIT:1>:<EOL><INDENT>assert val[<NUM_LIT:0>] == _chr(_DOLLAR_SIGN)<EOL><DEDENT>elif maybe_symbol_identifier:<EOL><INDENT>assert not maybe_ivm<EOL>sid = int(val[<NUM_LIT:1>:])<EOL>val = SymbolToken(None, sid)<EOL><DEDENT>elif complete_ivm:<EOL><INDENT>val = _IVMToken(*val.as_symbol())<EOL><DEDENT>yield _symbol_token_end(c, ctx, is_field_name, value=val)<EOL>
Handles symbol tokens that begin with a dollar sign. These may end up being system symbols ($ion_*), symbol identifiers ('$' DIGITS+), or regular unquoted symbols.
f5017:m33
def _quoted_text_handler_factory(delimiter, assertion, before, after, append_first=True,<EOL>on_close=lambda ctx: None):
@coroutine<EOL>def quoted_text_handler(c, ctx, is_field_name=False):<EOL><INDENT>assert assertion(c)<EOL>def append():<EOL><INDENT>if not _is_escaped_newline(c):<EOL><INDENT>val.append(c)<EOL><DEDENT><DEDENT>is_clob = ctx.ion_type is IonType.CLOB<EOL>max_char = _MAX_CLOB_CHAR if is_clob else _MAX_TEXT_CHAR<EOL>ctx.set_unicode(quoted_text=True)<EOL>val, event_on_close = before(c, ctx, is_field_name, is_clob)<EOL>if append_first:<EOL><INDENT>append()<EOL><DEDENT>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>done = False<EOL>while not done:<EOL><INDENT>if c == delimiter and not _is_escaped(c):<EOL><INDENT>done = True<EOL>if event_on_close:<EOL><INDENT>trans = on_close(ctx)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_validate_short_quoted_text(c, ctx, max_char)<EOL>append()<EOL><DEDENT>c, _ = yield trans<EOL><DEDENT>yield after(c, ctx, is_field_name)<EOL><DEDENT>return quoted_text_handler<EOL>
Generates handlers for quoted text tokens (either short strings or quoted symbols). Args: delimiter (int): Ordinal of the quoted text's delimiter. assertion (callable): Accepts the first character's ordinal, returning True if that character is a legal beginning to the token. before (callable): Called upon initialization. Accepts the first character's ordinal, the current context, True if the token is a field name, and True if the token is a clob; returns the token's current value and True if ``on_close`` should be called upon termination of the token. after (callable): Called after termination of the token. Accepts the final character's ordinal, the current context, and True if the token is a field name; returns a Transition. append_first (Optional[bool]): True if the first character the coroutine receives is part of the text data, and should therefore be appended to the value; otherwise, False (in which case, the first character must be the delimiter). on_close (Optional[callable]): Called upon termination of the token (before ``after``), if ``before`` indicated that ``on_close`` should be called. Accepts the current context and returns a Transition. This is useful for yielding a different kind of Transition based on initialization parameters given to ``before`` (e.g. string vs. clob).
f5017:m34
def _short_string_handler_factory():
def before(c, ctx, is_field_name, is_clob):<EOL><INDENT>assert not (is_clob and is_field_name)<EOL>is_string = not is_clob and not is_field_name<EOL>if is_string:<EOL><INDENT>ctx.set_ion_type(IonType.STRING)<EOL><DEDENT>val = ctx.value<EOL>if is_field_name:<EOL><INDENT>assert not val<EOL>ctx.set_pending_symbol()<EOL>val = ctx.pending_symbol<EOL><DEDENT>return val, is_string<EOL><DEDENT>def on_close(ctx):<EOL><INDENT>ctx.set_self_delimiting(True)<EOL>return ctx.event_transition(IonEvent, IonEventType.SCALAR, ctx.ion_type, ctx.value.as_text())<EOL><DEDENT>def after(c, ctx, is_field_name):<EOL><INDENT>ctx.set_quoted_text(False).set_self_delimiting(True)<EOL>return ctx.immediate_transition(<EOL>ctx.whence if is_field_name else _clob_end_handler(c, ctx),<EOL>)<EOL><DEDENT>return _quoted_text_handler_factory(_DOUBLE_QUOTE, lambda c: c == _DOUBLE_QUOTE, before, after, append_first=False,<EOL>on_close=on_close)<EOL>
Generates the short string (double quoted) handler.
f5017:m35
def _quoted_symbol_handler_factory():
def before(c, ctx, is_field_name, is_clob):<EOL><INDENT>assert not is_clob<EOL>_validate_short_quoted_text(c, ctx, _MAX_TEXT_CHAR)<EOL>return ctx.value, False<EOL><DEDENT>return _quoted_text_handler_factory(<EOL>_SINGLE_QUOTE,<EOL>lambda c: (c != _SINGLE_QUOTE or _is_escaped(c)),<EOL>before,<EOL>_symbol_token_end,<EOL>)<EOL>
Generates the quoted symbol (single quoted) handler.
f5017:m36
def _single_quote_handler_factory(on_single_quote, on_other):
@coroutine<EOL>def single_quote_handler(c, ctx, is_field_name=False):<EOL><INDENT>assert c == _SINGLE_QUOTE<EOL>c, self = yield<EOL>if c == _SINGLE_QUOTE and not _is_escaped(c):<EOL><INDENT>yield on_single_quote(c, ctx, is_field_name)<EOL><DEDENT>else:<EOL><INDENT>ctx.set_unicode(quoted_text=True)<EOL>yield on_other(c, ctx, is_field_name)<EOL><DEDENT><DEDENT>return single_quote_handler<EOL>
Generates handlers used for classifying tokens that begin with one or more single quotes. Args: on_single_quote (callable): Called when another single quote is found. Accepts the current character's ordinal, the current context, and True if the token is a field name; returns a Transition. on_other (callable): Called when any character other than a single quote is found. Accepts the current character's ordinal, the current context, and True if the token is a field name; returns a Transition.
f5017:m37
@coroutine<EOL>def _struct_or_lob_handler(c, ctx):
assert c == _OPEN_BRACE<EOL>c, self = yield<EOL>yield ctx.immediate_transition(_STRUCT_OR_LOB_TABLE[c](c, ctx))<EOL>
Handles tokens that begin with an open brace.
f5017:m38
@coroutine<EOL>def _lob_start_handler(c, ctx):
assert c == _OPEN_BRACE<EOL>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>quotes = <NUM_LIT:0><EOL>while True:<EOL><INDENT>if c in _WHITESPACE:<EOL><INDENT>if quotes > <NUM_LIT:0>:<EOL><INDENT>_illegal_character(c, ctx)<EOL><DEDENT><DEDENT>elif c == _DOUBLE_QUOTE:<EOL><INDENT>if quotes > <NUM_LIT:0>:<EOL><INDENT>_illegal_character(c, ctx)<EOL><DEDENT>ctx.set_ion_type(IonType.CLOB).set_unicode(quoted_text=True)<EOL>yield ctx.immediate_transition(_short_string_handler(c, ctx))<EOL><DEDENT>elif c == _SINGLE_QUOTE:<EOL><INDENT>if not quotes:<EOL><INDENT>ctx.set_ion_type(IonType.CLOB).set_unicode(quoted_text=True)<EOL><DEDENT>quotes += <NUM_LIT:1><EOL>if quotes == <NUM_LIT:3>:<EOL><INDENT>yield ctx.immediate_transition(_long_string_handler(c, ctx))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield ctx.immediate_transition(_blob_end_handler(c, ctx))<EOL><DEDENT>c, _ = yield trans<EOL><DEDENT>
Handles tokens that begin with two open braces.
f5017:m41
def _lob_end_handler_factory(ion_type, action, validate=lambda c, ctx, action_res: None):
assert ion_type is IonType.BLOB or ion_type is IonType.CLOB<EOL>@coroutine<EOL>def lob_end_handler(c, ctx):<EOL><INDENT>val = ctx.value<EOL>prev = c<EOL>action_res = None<EOL>if c != _CLOSE_BRACE and c not in _WHITESPACE:<EOL><INDENT>action_res = action(c, ctx, prev, action_res, True)<EOL><DEDENT>c, self = yield<EOL>trans = ctx.immediate_transition(self)<EOL>while True:<EOL><INDENT>if c in _WHITESPACE:<EOL><INDENT>if prev == _CLOSE_BRACE:<EOL><INDENT>_illegal_character(c, ctx.set_ion_type(ion_type), '<STR_LIT>')<EOL><DEDENT><DEDENT>elif c == _CLOSE_BRACE:<EOL><INDENT>if prev == _CLOSE_BRACE:<EOL><INDENT>validate(c, ctx, action_res)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>action_res = action(c, ctx, prev, action_res, False)<EOL><DEDENT>prev = c<EOL>c, _ = yield trans<EOL><DEDENT>ctx.set_self_delimiting(True) <EOL>yield ctx.event_transition(IonThunkEvent, IonEventType.SCALAR, ion_type, _parse_lob(ion_type, val))<EOL><DEDENT>return lob_end_handler<EOL>
Generates handlers for the end of blob or clob values. Args: ion_type (IonType): The type of this lob (either blob or clob). action (callable): Called for each non-whitespace, non-closing brace character encountered before the end of the lob. Accepts the current character's ordinal, the current context, the previous character's ordinal, the result of the previous call to ``action`` (if any), and True if this is the first call to ``action``. Returns any state that will be needed by subsequent calls to ``action``. For blobs, this should validate the character is valid base64; for clobs, this should ensure there are no illegal characters (e.g. comments) between the end of the data and the end of the clob. validate (Optional[callable]): Called once the second closing brace has been found. Accepts the current character's ordinal, the current context, and the result of the last call to ``action``; raises an error if this is not a valid lob value.
f5017:m42
def _blob_end_handler_factory():
def expand_res(res):<EOL><INDENT>if res is None:<EOL><INDENT>return <NUM_LIT:0>, <NUM_LIT:0><EOL><DEDENT>return res<EOL><DEDENT>def action(c, ctx, prev, res, is_first):<EOL><INDENT>num_digits, num_pads = expand_res(res)<EOL>if c in _BASE64_DIGITS:<EOL><INDENT>if prev == _CLOSE_BRACE or prev == _BASE64_PAD:<EOL><INDENT>_illegal_character(c, ctx.set_ion_type(IonType.BLOB))<EOL><DEDENT>num_digits += <NUM_LIT:1><EOL><DEDENT>elif c == _BASE64_PAD:<EOL><INDENT>if prev == _CLOSE_BRACE:<EOL><INDENT>_illegal_character(c, ctx.set_ion_type(IonType.BLOB))<EOL><DEDENT>num_pads += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>_illegal_character(c, ctx.set_ion_type(IonType.BLOB))<EOL><DEDENT>ctx.value.append(c)<EOL>return num_digits, num_pads<EOL><DEDENT>def validate(c, ctx, res):<EOL><INDENT>num_digits, num_pads = expand_res(res)<EOL>if num_pads > <NUM_LIT:3> or (num_digits + num_pads) % <NUM_LIT:4> != <NUM_LIT:0>:<EOL><INDENT>_illegal_character(c, ctx, '<STR_LIT>'<EOL>% (num_pads, num_digits))<EOL><DEDENT><DEDENT>return _lob_end_handler_factory(IonType.BLOB, action, validate)<EOL>
Generates the handler for the end of a blob value. This includes the base-64 data and the two closing braces.
f5017:m43
def _clob_end_handler_factory():
def action(c, ctx, prev, res, is_first):<EOL><INDENT>if is_first and ctx.is_self_delimiting and c == _DOUBLE_QUOTE:<EOL><INDENT>assert c is prev<EOL>return res<EOL><DEDENT>_illegal_character(c, ctx)<EOL><DEDENT>return _lob_end_handler_factory(IonType.CLOB, action)<EOL>
Generates the handler for the end of a clob value. This includes anything from the data's closing quote through the second closing brace.
f5017:m44
def _container_start_handler_factory(ion_type, before_yield=lambda c, ctx: None):
assert ion_type.is_container<EOL>@coroutine<EOL>def container_start_handler(c, ctx):<EOL><INDENT>before_yield(c, ctx)<EOL>yield<EOL>yield ctx.event_transition(IonEvent, IonEventType.CONTAINER_START, ion_type, value=None)<EOL><DEDENT>return container_start_handler<EOL>
Generates handlers for tokens that begin with container start characters. Args: ion_type (IonType): The type of this container. before_yield (Optional[callable]): Called at initialization. Accepts the first character's ordinal and the current context; performs any necessary initialization actions.
f5017:m45
@coroutine<EOL>def _read_data_handler(whence, ctx, complete, can_flush):
trans = None<EOL>queue = ctx.queue<EOL>while True:<EOL><INDENT>data_event, self = (yield trans)<EOL>if data_event is not None:<EOL><INDENT>if data_event.data is not None:<EOL><INDENT>data = data_event.data<EOL>data_len = len(data)<EOL>if data_len > <NUM_LIT:0>:<EOL><INDENT>queue.extend(data)<EOL>yield Transition(None, whence)<EOL><DEDENT><DEDENT>elif data_event.type is ReadEventType.NEXT:<EOL><INDENT>queue.mark_eof()<EOL>if not can_flush:<EOL><INDENT>_illegal_character(queue.read_byte(), ctx, "<STR_LIT>")<EOL><DEDENT>yield Transition(None, whence)<EOL><DEDENT><DEDENT>trans = Transition(complete and ION_STREAM_END_EVENT or ION_STREAM_INCOMPLETE_EVENT, self)<EOL><DEDENT>
Creates a co-routine for retrieving data up to a requested size. Args: whence (Coroutine): The co-routine to return to after the data is satisfied. ctx (_HandlerContext): The context for the read. complete (True|False): True if STREAM_END should be emitted if no bytes are read or available; False if INCOMPLETE should be emitted in that case. can_flush (True|False): True if NEXT may be requested after INCOMPLETE is emitted as a result of this data request.
f5017:m46
@coroutine<EOL>def _container_handler(c, ctx):
_, self = (yield None)<EOL>queue = ctx.queue<EOL>child_context = None<EOL>is_field_name = ctx.ion_type is IonType.STRUCT<EOL>delimiter_required = False<EOL>complete = ctx.depth == <NUM_LIT:0><EOL>can_flush = False<EOL>def has_pending_symbol():<EOL><INDENT>return child_context and child_context.pending_symbol is not None<EOL><DEDENT>def symbol_value_event():<EOL><INDENT>return child_context.event_transition(<EOL>IonEvent, IonEventType.SCALAR, IonType.SYMBOL, _as_symbol(child_context.pending_symbol))<EOL><DEDENT>def pending_symbol_value():<EOL><INDENT>if has_pending_symbol():<EOL><INDENT>assert not child_context.value<EOL>if ctx.ion_type is IonType.STRUCT and child_context.field_name is None:<EOL><INDENT>_illegal_character(c, ctx,<EOL>'<STR_LIT>' % (child_context.pending_symbol,))<EOL><DEDENT>return symbol_value_event()<EOL><DEDENT>return None<EOL><DEDENT>def is_value_decorated():<EOL><INDENT>return child_context is not None and (child_context.annotations or child_context.field_name is not None)<EOL><DEDENT>def _can_flush():<EOL><INDENT>return child_context is not None andchild_context.depth == <NUM_LIT:0> and(<EOL>(<EOL>child_context.ion_type is not None and<EOL>(<EOL>child_context.ion_type.is_numeric or<EOL>(child_context.ion_type.is_text and not ctx.quoted_text and not is_field_name)<EOL>)<EOL>) or<EOL>(<EOL>child_context.line_comment and<EOL>not is_value_decorated()<EOL>)<EOL>)<EOL><DEDENT>while True:<EOL><INDENT>if c in ctx.container.end or c in ctx.container.delimiter or BufferQueue.is_eof(c):<EOL><INDENT>symbol_event = pending_symbol_value()<EOL>if symbol_event is not None:<EOL><INDENT>yield symbol_event<EOL>child_context = None<EOL>delimiter_required = ctx.container.is_delimited<EOL><DEDENT>if c in ctx.container.end:<EOL><INDENT>if not delimiter_required and is_value_decorated():<EOL><INDENT>_illegal_character(c, child_context,<EOL>'<STR_LIT>'<EOL>% (child_context.field_name, child_context.annotations))<EOL><DEDENT>yield Transition(<EOL>IonEvent(IonEventType.CONTAINER_END, ctx.ion_type, depth=ctx.depth-<NUM_LIT:1>),<EOL>ctx.whence<EOL>)<EOL>raise ValueError('<STR_LIT>')<EOL><DEDENT>elif c in ctx.container.delimiter:<EOL><INDENT>if not delimiter_required:<EOL><INDENT>_illegal_character(c, ctx.derive_child_context(None),<EOL>'<STR_LIT>'<EOL>% (_chr(ctx.container.delimiter[<NUM_LIT:0>]),))<EOL><DEDENT>is_field_name = ctx.ion_type is IonType.STRUCT<EOL>delimiter_required = False<EOL>c = None<EOL><DEDENT>else:<EOL><INDENT>assert BufferQueue.is_eof(c)<EOL>assert len(queue) == <NUM_LIT:0><EOL>yield ctx.read_data_event(self, complete=True)<EOL>c = None<EOL><DEDENT><DEDENT>if c is not None and c not in _WHITESPACE:<EOL><INDENT>can_flush = False<EOL>if c == _SLASH:<EOL><INDENT>if child_context is None:<EOL><INDENT>child_context = ctx.derive_child_context(self)<EOL><DEDENT>if ctx.ion_type is IonType.SEXP:<EOL><INDENT>handler = _sexp_slash_handler(c, child_context, pending_event=pending_symbol_value())<EOL><DEDENT>else:<EOL><INDENT>handler = _comment_handler(c, child_context, self)<EOL><DEDENT><DEDENT>elif delimiter_required:<EOL><INDENT>_illegal_character(c, ctx.derive_child_context(None), '<STR_LIT>'<EOL>% (_chr(ctx.container.delimiter[<NUM_LIT:0>]),))<EOL><DEDENT>elif has_pending_symbol():<EOL><INDENT>if c == _COLON:<EOL><INDENT>if is_field_name:<EOL><INDENT>is_field_name = False<EOL>child_context.set_field_name()<EOL>c = None<EOL><DEDENT>else:<EOL><INDENT>assert not ctx.quoted_text<EOL>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_event(self)<EOL><DEDENT>c = queue.read_byte()<EOL>if c == _COLON:<EOL><INDENT>child_context.set_annotation()<EOL>c = None <EOL><DEDENT>else:<EOL><INDENT>_illegal_character(c, child_context)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if is_field_name:<EOL><INDENT>_illegal_character(c, child_context, '<STR_LIT>'<EOL>% child_context.pending_symbol)<EOL><DEDENT>yield symbol_value_event()<EOL>child_context = None<EOL>delimiter_required = ctx.container.is_delimited<EOL><DEDENT>continue<EOL><DEDENT>else:<EOL><INDENT>if not is_value_decorated():<EOL><INDENT>child_context = ctx.derive_child_context(self)<EOL><DEDENT>if is_field_name:<EOL><INDENT>handler = _FIELD_NAME_START_TABLE[c](c, child_context)<EOL><DEDENT>else:<EOL><INDENT>handler = _VALUE_START_TABLE[c](c, child_context) <EOL>can_flush = _IMMEDIATE_FLUSH_TABLE[c]<EOL><DEDENT><DEDENT>container_start = c == _OPEN_BRACKET orc == _OPEN_PAREN <EOL>quoted_start = c == _DOUBLE_QUOTE or c == _SINGLE_QUOTE<EOL>while True:<EOL><INDENT>if container_start:<EOL><INDENT>c = None<EOL>container_start = False<EOL><DEDENT>else:<EOL><INDENT>if child_context.quoted_text or quoted_start:<EOL><INDENT>quoted_start = False<EOL>yield child_context.next_code_point(self)<EOL>c = child_context.code_point<EOL><DEDENT>else:<EOL><INDENT>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_event(self, can_flush=can_flush)<EOL><DEDENT>c = queue.read_byte()<EOL><DEDENT><DEDENT>trans = handler.send((c, handler))<EOL>if trans.event is not None:<EOL><INDENT>is_self_delimiting = False<EOL>if child_context.is_composite:<EOL><INDENT>next_transition = trans.next_transition<EOL>child_context = trans.next_context<EOL>assert next_transition is None or next_transition.event is None<EOL><DEDENT>else:<EOL><INDENT>next_transition = None<EOL>is_self_delimiting = child_context.is_self_delimiting<EOL>child_context = None<EOL><DEDENT>yield trans<EOL>event_ion_type = trans.event.ion_type <EOL>is_container = event_ion_type is not None and event_ion_type.is_container andtrans.event.event_type is not IonEventType.SCALAR<EOL>if is_container:<EOL><INDENT>assert next_transition is None<EOL>yield Transition(<EOL>None,<EOL>_container_handler(c, ctx.derive_container_context(trans.event.ion_type, self))<EOL>)<EOL><DEDENT>complete = ctx.depth == <NUM_LIT:0><EOL>can_flush = False<EOL>if is_container or is_self_delimiting:<EOL><INDENT>assert not ctx.quoted_text<EOL>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_event(self, complete, can_flush)<EOL><DEDENT>c = queue.read_byte()<EOL><DEDENT>delimiter_required = ctx.container.is_delimited<EOL>if next_transition is None:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>trans = next_transition<EOL><DEDENT><DEDENT>elif self is trans.delegate:<EOL><INDENT>child_context.set_ion_type(None) <EOL>complete = False<EOL>can_flush = _can_flush()<EOL>if is_field_name:<EOL><INDENT>assert not can_flush<EOL>if c == _COLON or not child_context.is_self_delimiting:<EOL><INDENT>break<EOL><DEDENT><DEDENT>elif has_pending_symbol():<EOL><INDENT>can_flush = ctx.depth == <NUM_LIT:0><EOL>if not child_context.is_self_delimiting or child_context.line_comment:<EOL><INDENT>break<EOL><DEDENT><DEDENT>elif child_context.is_self_delimiting:<EOL><INDENT>complete = ctx.depth == <NUM_LIT:0> and not is_value_decorated()<EOL><DEDENT>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_event(self, complete, can_flush)<EOL><DEDENT>c = queue.read_byte()<EOL>break<EOL><DEDENT>can_flush = _can_flush()<EOL>handler = trans.delegate<EOL><DEDENT><DEDENT>else:<EOL><INDENT>assert not ctx.quoted_text<EOL>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_event(self, complete, can_flush)<EOL><DEDENT>c = queue.read_byte()<EOL><DEDENT><DEDENT>
Coroutine for container values. Delegates to other coroutines to tokenize all child values.
f5017:m47
@coroutine<EOL>def _skip_trampoline(handler):
data_event, self = (yield None)<EOL>delegate = handler<EOL>event = None<EOL>depth = <NUM_LIT:0><EOL>while True:<EOL><INDENT>def pass_through():<EOL><INDENT>_trans = delegate.send(Transition(data_event, delegate))<EOL>return _trans, _trans.delegate, _trans.event<EOL><DEDENT>if data_event is not None and data_event.type is ReadEventType.SKIP:<EOL><INDENT>while True:<EOL><INDENT>trans, delegate, event = pass_through()<EOL>if event is not None:<EOL><INDENT>if event.event_type is IonEventType.CONTAINER_END and event.depth <= depth:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if event is None or event.event_type is IonEventType.INCOMPLETE:<EOL><INDENT>data_event, _ = yield Transition(event, self)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>trans, delegate, event = pass_through()<EOL>if event is not None and (event.event_type is IonEventType.CONTAINER_START or<EOL>event.event_type is IonEventType.CONTAINER_END):<EOL><INDENT>depth = event.depth<EOL><DEDENT><DEDENT>data_event, _ = yield Transition(event, self)<EOL><DEDENT>
Intercepts events from container handlers, emitting them only if they should not be skipped.
f5017:m48
@coroutine<EOL>def _next_code_point_handler(whence, ctx):
data_event, self = yield<EOL>queue = ctx.queue<EOL>unicode_escapes_allowed = ctx.ion_type is not IonType.CLOB<EOL>escaped_newline = False<EOL>escape_sequence = b'<STR_LIT>'<EOL>low_surrogate_required = False<EOL>while True:<EOL><INDENT>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_event(self)<EOL><DEDENT>queue_iter = iter(queue)<EOL>code_point_generator = _next_code_point_iter(queue, queue_iter)<EOL>code_point = next(code_point_generator)<EOL>if code_point == _BACKSLASH:<EOL><INDENT>escape_sequence += six.int2byte(_BACKSLASH)<EOL>num_digits = None<EOL>while True:<EOL><INDENT>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_event(self)<EOL><DEDENT>code_point = next(queue_iter)<EOL>if six.indexbytes(escape_sequence, -<NUM_LIT:1>) == _BACKSLASH:<EOL><INDENT>if code_point == _ord(b'<STR_LIT:u>') and unicode_escapes_allowed:<EOL><INDENT>num_digits = <NUM_LIT:12> if low_surrogate_required else <NUM_LIT:6><EOL>low_surrogate_required = False<EOL><DEDENT>elif low_surrogate_required:<EOL><INDENT>_illegal_character(code_point, ctx,<EOL>'<STR_LIT>' % (escape_sequence,))<EOL><DEDENT>elif code_point == _ord(b'<STR_LIT:x>'):<EOL><INDENT>num_digits = <NUM_LIT:4> <EOL><DEDENT>elif code_point == _ord(b'<STR_LIT>') and unicode_escapes_allowed:<EOL><INDENT>num_digits = <NUM_LIT:10> <EOL><DEDENT>elif code_point in _COMMON_ESCAPES:<EOL><INDENT>if code_point == _SLASH or code_point == _QUESTION_MARK:<EOL><INDENT>escape_sequence = b'<STR_LIT>' <EOL><DEDENT>escape_sequence += six.int2byte(code_point)<EOL>break<EOL><DEDENT>elif code_point in _NEWLINES:<EOL><INDENT>escaped_newline = True<EOL>break<EOL><DEDENT>else:<EOL><INDENT>_illegal_character(code_point, ctx, '<STR_LIT>' % (_chr(code_point),))<EOL><DEDENT>escape_sequence += six.int2byte(code_point)<EOL><DEDENT>else:<EOL><INDENT>if code_point not in _HEX_DIGITS:<EOL><INDENT>_illegal_character(code_point, ctx,<EOL>'<STR_LIT>' % (_chr(code_point),))<EOL><DEDENT>escape_sequence += six.int2byte(code_point)<EOL>if len(escape_sequence) == num_digits:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if not escaped_newline:<EOL><INDENT>decoded_escape_sequence = escape_sequence.decode('<STR_LIT>')<EOL>cp_iter = _next_code_point_iter(decoded_escape_sequence, iter(decoded_escape_sequence), to_int=ord)<EOL>code_point = next(cp_iter)<EOL>if code_point is None:<EOL><INDENT>low_surrogate_required = True<EOL>continue<EOL><DEDENT>code_point = CodePoint(code_point)<EOL>code_point.char = decoded_escape_sequence<EOL>code_point.is_escaped = True<EOL>ctx.set_code_point(code_point)<EOL>yield Transition(None, whence)<EOL><DEDENT><DEDENT>elif low_surrogate_required:<EOL><INDENT>_illegal_character(code_point, ctx, '<STR_LIT>' % (escape_sequence,))<EOL><DEDENT>if code_point == _CARRIAGE_RETURN:<EOL><INDENT>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_event(self)<EOL><DEDENT>code_point = next(queue_iter)<EOL>if code_point != _NEWLINE:<EOL><INDENT>queue.unread(code_point)<EOL>code_point = _NEWLINE<EOL><DEDENT><DEDENT>while code_point is None:<EOL><INDENT>yield ctx.read_data_event(self)<EOL>code_point = next(code_point_generator)<EOL><DEDENT>if escaped_newline:<EOL><INDENT>code_point = CodePoint(code_point)<EOL>code_point.char = _ESCAPED_NEWLINE<EOL>code_point.is_escaped = True<EOL><DEDENT>ctx.set_code_point(code_point)<EOL>yield Transition(None, whence)<EOL><DEDENT>
Retrieves the next code point from within a quoted string or symbol.
f5017:m49
def reader(queue=None, is_unicode=False):
if queue is None:<EOL><INDENT>queue = BufferQueue(is_unicode)<EOL><DEDENT>ctx = _HandlerContext(<EOL>container=_C_TOP_LEVEL,<EOL>queue=queue,<EOL>field_name=None,<EOL>annotations=None,<EOL>depth=<NUM_LIT:0>,<EOL>whence=None,<EOL>value=None,<EOL>ion_type=None, <EOL>pending_symbol=None<EOL>)<EOL>return reader_trampoline(_skip_trampoline(_container_handler(None, ctx)), allow_flush=True)<EOL>
Returns a raw binary reader co-routine. Args: queue (Optional[BufferQueue]): The buffer read data for parsing, if ``None`` a new one will be created. is_unicode (Optional[bool]): True if all input data to this reader will be of unicode text type; False if all input data to this reader will be of binary type. Yields: IonEvent: parse events, will have an event type of ``INCOMPLETE`` if data is needed in the middle of a value or ``STREAM_END`` if there is no data **and** the parser is not in the middle of parsing a value. Receives :class:`DataEvent`, with :class:`ReadEventType` of ``NEXT`` or ``SKIP`` to iterate over values; ``DATA`` or ``NEXT`` if the last event type was ``INCOMPLETE``; or ``DATA`` if the last event type was ``STREAM_END``. When the reader receives ``NEXT`` after yielding ``INCOMPLETE``, this signals to the reader that no further data is coming, and that any pending data should be flushed as either parse events or errors. This is **only** valid at the top-level, and will **only** result in a parse event if the last character encountered... * was a digit or a decimal point in a non-timestamp, non-keyword numeric value; OR * ended a valid partial timestamp; OR * ended a keyword value (special floats, booleans, ``null``, and typed nulls); OR * was part of an unquoted symbol token, or whitespace or the end of a comment following an unquoted symbol token (as long as no colons were encountered after the token); OR * was the closing quote of a quoted symbol token, or whitespace or the end of a comment following a quoted symbol token (as long as no colons were encountered after the token); OR * was the final closing quote of a long string, or whitespace or the end of a comment following a long string. If the reader successfully yields a parse event as a result of this, ``NEXT`` is the only input that may immediately follow. At that point, there are only two possible responses from the reader: * If the last character read was the closing quote of an empty symbol following a long string, the reader will emit a parse event representing a symbol value with empty text. The next reader input/output event pair must be (``NEXT``, ``STREAM_END``). * Otherwise, the reader will emit ``STREAM_END``. After that ``STREAM_END``, the user may later provide ``DATA`` to resume reading. If this occurs, the new data will be interpreted as if it were at the start of the stream (i.e. it can never continue the previous value), except that it occurs within the same symbol table context. This has the following implications (where ``<FLUSH>`` stands for the (``INCOMPLETE``, ``NEXT``) transaction): * If the previously-emitted value was a numeric value (``int``, ``float``, ``decimal``, ``timestamp``), the new data will never extend that value, even if it would be a valid continuation. For example, ``123<FLUSH>456`` will always be emitted as two parse events (ints ``123`` and ``456``), even though it would have been interpreted as ``123456`` without the ``<FLUSH>``. * If the previously-emitted value was a symbol value or long string, the new data will be interpreted as the start of a new value. For example, ``abc<FLUSH>::123`` will be emitted as the symbol value ``'abc'``, followed by an error upon encountering ':' at the start of a value, even though it would have been interpreted as the ``int`` ``123`` annotated with ``'abc'`` without the ``<FLUSH>``. The input ``abc<FLUSH>abc`` will be emitted as the symbol value ``'abc'`` (represented by a :class:`SymbolToken`), followed by another symbol value ``'abc'`` (represented by a ``SymbolToken`` with the same symbol ID), even though it would have been interpreted as ``'abcabc'`` without the ``<FLUSH>``. Similarly, ``'''abc'''<FLUSH>'''def'''`` will the interpreted as two strings (``'abc'`` and ``'def'``), even though it would have been interpreted as ``'abcdef'`` without the ``<FLUSH>``. ``SKIP`` is only allowed within a container. A reader is *in* a container when the ``CONTAINER_START`` event type is encountered and *not in* a container when the ``CONTAINER_END`` event type for that container is encountered.
f5017:m50
def event_transition(self, event_cls, event_type, ion_type, value):
annotations = self.annotations or ()<EOL>depth = self.depth<EOL>whence = self.whence<EOL>if ion_type is IonType.SYMBOL:<EOL><INDENT>if not annotations and depth == <NUM_LIT:0> and isinstance(value, _IVMToken):<EOL><INDENT>event = value.ivm_event()<EOL>if event is None:<EOL><INDENT>_illegal_character(None, self, '<STR_LIT>' % (value.text,))<EOL><DEDENT>return Transition(event, whence)<EOL><DEDENT>assert not isinstance(value, _IVMToken)<EOL><DEDENT>return Transition(<EOL>event_cls(event_type, ion_type, value, self.field_name, annotations, depth),<EOL>whence<EOL>)<EOL>
Returns an ion event event_transition that yields to another co-routine.
f5017:c2:m1
def immediate_transition(self, delegate):
return Transition(None, delegate)<EOL>
Returns an immediate transition to another co-routine.
f5017:c2:m2
def read_data_event(self, whence, complete=False, can_flush=False):
return Transition(None, _read_data_handler(whence, self, complete, can_flush))<EOL>
Creates a transition to a co-routine for retrieving data as bytes. Args: whence (Coroutine): The co-routine to return to after the data is satisfied. complete (Optional[bool]): True if STREAM_END should be emitted if no bytes are read or available; False if INCOMPLETE should be emitted in that case. can_flush (Optional[bool]): True if NEXT may be requested after INCOMPLETE is emitted as a result of this data request.
f5017:c2:m3
def next_code_point(self, whence):
return Transition(None, _next_code_point_handler(whence, self))<EOL>
Creates a co-routine for retrieving data as code points. This should be used in quoted string contexts.
f5017:c2:m4
def set_unicode(self, quoted_text=False):
if isinstance(self.value, CodePointArray):<EOL><INDENT>assert self.quoted_text == quoted_text<EOL>return self<EOL><DEDENT>self.value = CodePointArray(self.value)<EOL>self.quoted_text = quoted_text<EOL>self.line_comment = False<EOL>return self<EOL>
Converts the context's ``value`` to a sequence of unicode code points for holding text tokens, indicating whether the text is quoted.
f5017:c2:m5
def set_quoted_text(self, quoted_text):
self.quoted_text = quoted_text<EOL>self.line_comment = False<EOL>return self<EOL>
Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text tokens.
f5017:c2:m6
def set_self_delimiting(self, is_self_delimiting):
self.is_self_delimiting = is_self_delimiting<EOL>return self<EOL>
Sets the context's ``is_self_delimiting`` flag. Useful when the end of a self-delimiting token (short string, container, or comment) is reached. This is distinct from the ``quoted_text`` flag because some quoted text (quoted symbols and long strings) are not self-delimiting--they require lookahead to determine if they are complete.
f5017:c2:m7
def set_code_point(self, code_point):
self.code_point = code_point<EOL>return self<EOL>
Sets the context's current ``code_point`` to the given ``int`` or :class:`CodePoint`.
f5017:c2:m8
def derive_container_context(self, ion_type, whence):
if ion_type is IonType.STRUCT:<EOL><INDENT>container = _C_STRUCT<EOL><DEDENT>elif ion_type is IonType.LIST:<EOL><INDENT>container = _C_LIST<EOL><DEDENT>elif ion_type is IonType.SEXP:<EOL><INDENT>container = _C_SEXP<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % (ion_type.name,))<EOL><DEDENT>return _HandlerContext(<EOL>container=container,<EOL>queue=self.queue,<EOL>field_name=self.field_name,<EOL>annotations=self.annotations,<EOL>depth=self.depth + <NUM_LIT:1>,<EOL>whence=whence,<EOL>value=None, <EOL>ion_type=ion_type,<EOL>pending_symbol=None<EOL>)<EOL>
Derives a container context as a child of the current context.
f5017:c2:m9
def set_empty_symbol(self):
self.field_name = None<EOL>self.annotations = None<EOL>self.ion_type = None<EOL>self.set_pending_symbol(CodePointArray())<EOL>return self<EOL>
Resets the context, retaining the fields that make it a child of its container (``container``, ``queue``, ``depth``, ``whence``), and sets an empty ``pending_symbol``. This is useful when an empty quoted symbol immediately follows a long string.
f5017:c2:m10
def derive_child_context(self, whence):
return _HandlerContext(<EOL>container=self.container,<EOL>queue=self.queue,<EOL>field_name=None,<EOL>annotations=None,<EOL>depth=self.depth,<EOL>whence=whence,<EOL>value=bytearray(), <EOL>ion_type=None,<EOL>pending_symbol=None<EOL>)<EOL>
Derives a scalar context as a child of the current context.
f5017:c2:m11
def set_line_comment(self, is_line_comment=True):
self.line_comment = is_line_comment<EOL>return self<EOL>
Sets the context's ``line_comment`` flag. Useful when entering or exiting a line comment.
f5017:c2:m12
def set_ion_type(self, ion_type):
if ion_type is self.ion_type:<EOL><INDENT>return self<EOL><DEDENT>self.ion_type = ion_type<EOL>self.line_comment = False<EOL>return self<EOL>
Sets context to the given IonType.
f5017:c2:m13
def set_annotation(self):
assert self.pending_symbol is not None<EOL>assert not self.value<EOL>annotations = (_as_symbol(self.pending_symbol, is_symbol_value=False),) <EOL>self.annotations = annotations if not self.annotations else self.annotations + annotations<EOL>self.ion_type = None<EOL>self.pending_symbol = None <EOL>self.quoted_text = False<EOL>self.line_comment = False<EOL>self.is_self_delimiting = False<EOL>return self<EOL>
Appends the context's ``pending_symbol`` to its ``annotations`` sequence.
f5017:c2:m14
def set_field_name(self):
assert self.pending_symbol is not None<EOL>assert not self.value<EOL>self.field_name = _as_symbol(self.pending_symbol, is_symbol_value=False) <EOL>self.pending_symbol = None <EOL>self.quoted_text = False<EOL>self.line_comment = False<EOL>self.is_self_delimiting = False<EOL>return self<EOL>
Sets the context's ``pending_symbol`` as its ``field_name``.
f5017:c2:m15
def set_pending_symbol(self, pending_symbol=None):
if pending_symbol is None:<EOL><INDENT>pending_symbol = CodePointArray()<EOL><DEDENT>self.value = bytearray() <EOL>self.pending_symbol = pending_symbol<EOL>self.line_comment = False<EOL>return self<EOL>
Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``. If the input is None, an empty :class:`CodePointArray` is used.
f5017:c2:m16
def ivm_event(self):
try:<EOL><INDENT>return _IVM_EVENTS[self.text]<EOL><DEDENT>except KeyError:<EOL><INDENT>return None<EOL><DEDENT>
If this token's text is a supported IVM, returns the :class:`IonEvent` representing that IVM. Otherwise, returns `None`.
f5017:c6:m0
def regular_token(self):
return SymbolToken(self.text, self.sid, self.location)<EOL>
Returns a copy of this token as a normal :class:`SymbolToken`. This will be used in _as_symbol when this token is used as an annotation or field name, in which cases it can no longer be an IVM.
f5017:c6:m1
@coroutine<EOL>def managed_reader(reader, catalog=None):
if catalog is None:<EOL><INDENT>catalog = SymbolTableCatalog()<EOL><DEDENT>ctx = _ManagedContext(catalog)<EOL>symbol_trans = Transition(None, None)<EOL>ion_event = None<EOL>while True:<EOL><INDENT>if symbol_trans.delegate is not Noneand ion_event is not Noneand not ion_event.event_type.is_stream_signal:<EOL><INDENT>delegate = symbol_trans.delegate<EOL>symbol_trans = delegate.send(Transition(ion_event, delegate))<EOL>if symbol_trans.delegate is None:<EOL><INDENT>ctx = symbol_trans.event<EOL>data_event = NEXT_EVENT<EOL><DEDENT>else:<EOL><INDENT>data_event = symbol_trans.event<EOL><DEDENT><DEDENT>else:<EOL><INDENT>data_event = None<EOL>if ion_event is not None:<EOL><INDENT>event_type = ion_event.event_type<EOL>ion_type = ion_event.ion_type<EOL>depth = ion_event.depth<EOL>if depth == <NUM_LIT:0>:<EOL><INDENT>if event_type is IonEventType.VERSION_MARKER:<EOL><INDENT>if ion_event != ION_VERSION_MARKER_EVENT:<EOL><INDENT>raise IonException('<STR_LIT>' % (ion_event,))<EOL><DEDENT>ctx = _ManagedContext(ctx.catalog)<EOL>data_event = NEXT_EVENT<EOL><DEDENT>elif ion_type is IonType.SYMBOLand len(ion_event.annotations) == <NUM_LIT:0>and ion_event.value is not Noneand ctx.resolve(ion_event.value).text == TEXT_ION_1_0:<EOL><INDENT>assert symbol_trans.delegate is None<EOL>data_event = NEXT_EVENT<EOL><DEDENT>elif event_type is IonEventType.CONTAINER_STARTand ion_type is IonType.STRUCTand ctx.has_symbol_table_annotation(ion_event.annotations):<EOL><INDENT>assert symbol_trans.delegate is None<EOL>delegate = _local_symbol_table_handler(ctx)<EOL>symbol_trans = Transition(None, delegate)<EOL>data_event = NEXT_EVENT<EOL><DEDENT><DEDENT><DEDENT>if data_event is None:<EOL><INDENT>if ion_event is not None:<EOL><INDENT>ion_event = _managed_thunk_event(ctx, ion_event)<EOL><DEDENT>data_event = yield ion_event<EOL><DEDENT><DEDENT>ion_event = reader.send(data_event)<EOL><DEDENT>
Managed reader wrapping another reader. Args: reader (Coroutine): The underlying non-blocking reader co-routine. catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving imports. Yields: Events from the underlying reader delegating to symbol table processing as needed. The user will never see things like version markers or local symbol tables.
f5018:m5
def resolve(self, token):
if token.text is not None:<EOL><INDENT>return token<EOL><DEDENT>resolved_token = self.symbol_table.get(token.sid, None)<EOL>if resolved_token is None:<EOL><INDENT>raise IonException('<STR_LIT>' % token.sid)<EOL><DEDENT>return resolved_token<EOL>
Attempts to resolve the :class:`SymbolToken` against the current table. If the ``text`` is not None, the token is returned, otherwise, a token in the table is attempted to be retrieved. If not token is found, then this method will raise.
f5018:c0:m0
def is_null(value):
return value is None or isinstance(value, IonPyNull)<EOL>
A mechanism to determine if a value is ``None`` or an Ion ``null``.
f5020:m1
def _copy(self):
args, kwargs = self._to_constructor_args(self)<EOL>value = self.__class__(*args, **kwargs)<EOL>value.ion_event = None<EOL>value.ion_type = self.ion_type<EOL>value.ion_annotations = self.ion_annotations<EOL>return value<EOL>
Copies this instance. Its IonEvent (if any) is not preserved. Keeping this protected until/unless we decide there's use for it publicly.
f5020:c0:m1
@classmethod<EOL><INDENT>def from_event(cls, ion_event):<DEDENT>
if ion_event.value is not None:<EOL><INDENT>args, kwargs = cls._to_constructor_args(ion_event.value)<EOL><DEDENT>else:<EOL><INDENT>args, kwargs = (), {}<EOL><DEDENT>value = cls(*args, **kwargs)<EOL>value.ion_event = ion_event<EOL>value.ion_type = ion_event.ion_type<EOL>value.ion_annotations = ion_event.annotations<EOL>return value<EOL>
Constructs the given native extension from the properties of an event. Args: ion_event (IonEvent): The event to construct the native value from.
f5020:c0:m3
@classmethod<EOL><INDENT>def from_value(cls, ion_type, value, annotations=()):<DEDENT>
if value is None:<EOL><INDENT>value = IonPyNull()<EOL><DEDENT>else:<EOL><INDENT>args, kwargs = cls._to_constructor_args(value)<EOL>value = cls(*args, **kwargs)<EOL><DEDENT>value.ion_event = None<EOL>value.ion_type = ion_type<EOL>value.ion_annotations = annotations<EOL>return value<EOL>
Constructs a value as a copy with an associated Ion type and annotations. Args: ion_type (IonType): The associated Ion type. value (Any): The value to construct from, generally of type ``cls``. annotations (Sequence[unicode]): The sequence Unicode strings decorating this value.
f5020:c0:m4
def to_event(self, event_type, field_name=None, depth=None):
if self.ion_event is None:<EOL><INDENT>value = self<EOL>if isinstance(self, IonPyNull):<EOL><INDENT>value = None<EOL><DEDENT>self.ion_event = IonEvent(event_type, ion_type=self.ion_type, value=value, field_name=field_name,<EOL>annotations=self.ion_annotations, depth=depth)<EOL><DEDENT>return self.ion_event<EOL>
Constructs an IonEvent from this _IonNature value. Args: event_type (IonEventType): The type of the resulting event. field_name (Optional[text]): The field name associated with this value, if any. depth (Optional[int]): The depth of this value. Returns: An IonEvent with the properties from this value.
f5020:c0:m5
def _serialize_scalar_from_string_representation_factory(type_name, types, str_func=str):
def serialize(ion_event):<EOL><INDENT>value = ion_event.value<EOL>validate_scalar_value(value, types)<EOL>return six.b(str_func(value))<EOL><DEDENT>serialize.__name__ = '<STR_LIT>' + type_name<EOL>return serialize<EOL>
Builds functions that leverage Python ``str()`` or similar functionality. Args: type_name (str): The name of the Ion type. types (Union[Sequence[type],type]): The Python types to validate for. str_func (Optional[Callable]): The function to convert the value with, defaults to ``str``. Returns: function: The function for serializing scalars of a given type to Ion text bytes.
f5021:m1
def _serialize_container_factory(suffix, container_map):
def serialize(ion_event):<EOL><INDENT>if not ion_event.ion_type.is_container:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>return container_map[ion_event.ion_type]<EOL><DEDENT>serialize.__name__ = '<STR_LIT>' + suffix<EOL>return serialize<EOL>
Returns a function that serializes container start/end. Args: suffix (str): The suffix to name the function with. container_map (Dictionary[core.IonType, bytes]): The Returns: function: The closure for serialization.
f5021:m17
def raw_writer(indent=None):
is_whitespace_str = isinstance(indent, str) and re.search(r'<STR_LIT>', indent, re.M) is not None<EOL>if not (indent is None or is_whitespace_str):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>indent_bytes = six.b(indent) if isinstance(indent, str) else indent<EOL>return writer_trampoline(_raw_writer_coroutine(indent=indent_bytes))<EOL>
Returns a raw text writer co-routine. Yields: DataEvent: serialization events to write out Receives :class:`amazon.ion.core.IonEvent` or ``None`` when the co-routine yields ``HAS_PENDING`` :class:`WriteEventType` events.
f5021:m19
def convert(self, language, *args, **kwargs):
for f in find_pos(language):<EOL><INDENT>PoToXls(src=f, **kwargs).convert()<EOL><DEDENT>
Run converter. Args: language: (unicode) language code.
f5027:c0:m2
def __init__(self, src, *args, **kwargs):
self.quiet = kwargs.pop("<STR_LIT>", False)<EOL>if os.path.exists(src):<EOL><INDENT>self.src = src<EOL><DEDENT>else:<EOL><INDENT>if not self.quiet:<EOL><INDENT>sys.stderr.write("<STR_LIT>".format(**{"<STR_LIT:src>": src, }))<EOL><DEDENT>self.logger.error("<STR_LIT>".format(**{"<STR_LIT:src>": src, }))<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>self.po = polib.pofile(self.src)<EOL>self.result = xlwt.Workbook(encoding="<STR_LIT:utf-8>")<EOL>
Init conversion. Args: src: (unicode or string) path to ".po" file.
f5030:c0:m0
def header(self, sheet, name):
header = sheet.row(<NUM_LIT:0>)<EOL>for i, column in enumerate(self.headers[name]):<EOL><INDENT>header.write(i, self.headers[name][i])<EOL><DEDENT>
Write sheet header. Args: sheet: (xlwt.Worksheet.Worksheet) instance of xlwt sheet. name: (unicode) name of sheet.
f5030:c0:m1
def output(self):
path, src = os.path.split(self.src)<EOL>src, ext = os.path.splitext(src)<EOL>return os.path.join(path, "<STR_LIT>".format(**{"<STR_LIT:src>": src, }))<EOL>
Create full path for excel file to save parsed translations strings. Returns: unicode: full path for excel file to save parsed translations strings.
f5030:c0:m2
def strings(self):
sheet = self.result.add_sheet("<STR_LIT>")<EOL>self.header(sheet, "<STR_LIT>")<EOL>n_row = <NUM_LIT:1> <EOL>for entry in self.po:<EOL><INDENT>row = sheet.row(n_row)<EOL>row.write(<NUM_LIT:0>, entry.msgid)<EOL>row.write(<NUM_LIT:1>, entry.msgstr)<EOL>n_row += <NUM_LIT:1><EOL>sheet.flush_row_data()<EOL><DEDENT>
Write strings sheet.
f5030:c0:m3
def metadata(self):
sheet = self.result.add_sheet("<STR_LIT>")<EOL>self.header(sheet, "<STR_LIT>")<EOL>n_row = <NUM_LIT:1> <EOL>for k in self.po.metadata:<EOL><INDENT>row = sheet.row(n_row)<EOL>row.write(<NUM_LIT:0>, k)<EOL>row.write(<NUM_LIT:1>, self.po.metadata[k])<EOL>n_row += <NUM_LIT:1><EOL>sheet.flush_row_data()<EOL><DEDENT>
Write metadata sheet.
f5030:c0:m4
def convert(self, *args, **kwargs):
self.strings()<EOL>self.metadata()<EOL>self.result.save(self.output())<EOL>
Yes it is, thanks captain.
f5030:c0:m5
def __init__(self, table=None, columns=None, row_columns=None, tab=None,<EOL>key_on=None, deliminator=None):
self._deliminator = self.DEFAULT_DELIMINATOR<EOL>self._tab = self.DEFAULT_TAB<EOL>self._row_columns = []<EOL>self._column_index = OrderedDict()<EOL>self.shared_tables = []<EOL>if columns:<EOL><INDENT>columns = list(columns)<EOL><DEDENT>if row_columns:<EOL><INDENT>row_columns = list(row_columns)<EOL><DEDENT>if not table:<EOL><INDENT>self.row_columns = columns or row_columns or []<EOL>self.table = []<EOL><DEDENT>elif isinstance(table, SeabornTable):<EOL><INDENT>columns = columns or table.columns.copy()<EOL>self.row_columns = table.row_columns<EOL>self.table = [SeabornRow(self._column_index, list(row) + [])<EOL>for row in table]<EOL><DEDENT>elif isinstance(table, list) and isinstance(table[<NUM_LIT:0>], SeabornRow):<EOL><INDENT>self._column_index = table[<NUM_LIT:0>].column_index<EOL>self._row_columns = list(table[<NUM_LIT:0>].column_index.keys())<EOL>self.table = table<EOL><DEDENT>elif isinstance(table, dict):<EOL><INDENT>temp = self.dict_to_obj(table, columns, row_columns,<EOL>key_on=key_on)<EOL>self._column_index, self.table = temp._column_index, temp.table<EOL>self._row_columns = list(self._column_index.keys())<EOL><DEDENT>elif isinstance(table, list):<EOL><INDENT>temp = self.list_to_obj(table, columns, row_columns,<EOL>key_on=key_on)<EOL>self._column_index, self.table = temp._column_index, temp.table<EOL>self._row_columns = list(self._column_index.keys())<EOL><DEDENT>elif getattr(table, '<STR_LIT>', None) is not None andgetattr(table, '<STR_LIT>', None) is not None:<EOL><INDENT>self.row_columns = row_columns or columns or table.headings<EOL>self.table = [SeabornRow(self._column_index,<EOL>[row[c] for c in self.row_columns])<EOL>for row in table]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._parameters = {}<EOL>self.tab = self.DEFAULT_TAB if tab is None else tab<EOL>self.deliminator = self.DEFAULT_DELIMINATOR if deliminator is Noneelse deliminator<EOL>self._key_on = None<EOL>self.key_on = key_on<EOL>self._columns = columns or self.row_columns<EOL>for column in self._columns:<EOL><INDENT>if column not in self._column_index:<EOL><INDENT>self.insert(None, column, None)<EOL><DEDENT><DEDENT>self.assert_valid()<EOL>
:param table: obj can be list of list or list of dict :param columns: list of str of the columns in the table :param row_columns: list of str if different then visible columns :param tab: str to include before every row :param key_on: tuple of str if assigned so table is accessed as dict :param deliminator: str to separate the columns such as , \t or |
f5033:c0:m0
@classmethod<EOL><INDENT>def list_to_obj(cls, list_, columns, row_columns=None, tab='<STR_LIT>',<EOL>key_on=None, no_header=False):<DEDENT>
if not list_:<EOL><INDENT>return cls(columns=columns, row_columns=row_columns, tab=tab,<EOL>key_on=key_on)<EOL><DEDENT>if getattr(list_[<NUM_LIT:0>], '<STR_LIT>', None) and not isinstance(list_[<NUM_LIT:0>], dict):<EOL><INDENT>row_columns = row_columns or columns or list_[<NUM_LIT:0>].keys()<EOL>column_index = cls._create_column_index(row_columns)<EOL>table = [SeabornRow(<EOL>column_index,<EOL>[getattr(row, col, None) for col in row_columns])<EOL>for row in list_]<EOL><DEDENT>elif isinstance(list_[<NUM_LIT:0>], dict):<EOL><INDENT>row_columns = row_columns or columns orcls._key_on_columns(key_on,<EOL>cls._get_normalized_columns(<EOL>list_))<EOL>column_index = cls._create_column_index(row_columns)<EOL>table = [SeabornRow(column_index,<EOL>[row.get(c, None) for c in row_columns])<EOL>for row in list_]<EOL><DEDENT>elif isinstance(list_[<NUM_LIT:0>], (list, tuple)) and no_header:<EOL><INDENT>row_columns = row_columns or columns orcls._key_on_columns(key_on, [<EOL>'<STR_LIT>' % i for i in range(len(list_[<NUM_LIT:0>]))])<EOL>column_index = cls._create_column_index(row_columns)<EOL>table = [SeabornRow(column_index, row) for row in list_]<EOL><DEDENT>elif isinstance(list_[<NUM_LIT:0>], (list, tuple)):<EOL><INDENT>row_columns = row_columns or list_[<NUM_LIT:0>]<EOL>if list_[<NUM_LIT:0>] == row_columns:<EOL><INDENT>list_ = list_[<NUM_LIT:1>:]<EOL><DEDENT>column_index = cls._create_column_index(row_columns)<EOL>size = len(row_columns)<EOL>table = [SeabornRow(column_index, row + [None] * (size - len(row)))<EOL>for row in list_]<EOL><DEDENT>else:<EOL><INDENT>column_index = cls._create_column_index(columns or [])<EOL>table = [SeabornRow(column_index, [row]) for row in list_]<EOL><DEDENT>return cls(table, columns, row_columns, tab, key_on)<EOL>
:param list_: list of list or list of dictionary to use as the source :param columns: list of strings to label the columns when converting to str :param row_columns: list of columns in the actually data :param tab: str of the tab to use before the row when converting to str :param key_on: str of the column to key each row on :param no_header: bool if false then the first row is the headers :return: SeabornTable
f5033:c0:m1
@classmethod<EOL><INDENT>def dict_to_obj(cls, dict_, columns, row_columns, tab='<STR_LIT>', key_on=None):<DEDENT>
if isinstance(list(dict_.values())[<NUM_LIT:0>], dict):<EOL><INDENT>row_columns = row_columns or columns or cls._key_on_columns(<EOL>key_on, cls._ordered_keys(dict_.values()[<NUM_LIT:0>]))<EOL>column_index = cls._create_column_index(row_columns)<EOL>if key_on is None:<EOL><INDENT>table = [<EOL>SeabornRow(column_index, [row[c] for c in row_columns])<EOL>for row in dict_.values()]<EOL><DEDENT>else:<EOL><INDENT>table = [SeabornRow(column_index,<EOL>[row.get(c, c == key_on and key or None)<EOL>for c in row_columns])<EOL>for key, row in dict_.items()]<EOL><DEDENT><DEDENT>elif isinstance(list(dict_.values())[<NUM_LIT:0>], list):<EOL><INDENT>row_columns = row_columns or columns orcls._key_on_columns(key_on, sorted(dict_.keys()))<EOL>column_index = cls._create_column_index(row_columns)<EOL>if key_on is None:<EOL><INDENT>table = [<EOL>SeabornRow(column_index, [dict_[c][i] for c in columns])<EOL>for i in range(len(dict_[columns[<NUM_LIT:0>]]))]<EOL><DEDENT>else:<EOL><INDENT>table = [<EOL>SeabornRow(column_index, [dict_[c][i] for c in columns])<EOL>for i in range(len(dict_[columns[<NUM_LIT:0>]]))]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>row_columns = row_columns or columns or ['<STR_LIT>', '<STR_LIT>']<EOL>column_index = cls._create_column_index(row_columns)<EOL>table = [SeabornRow(column_index, [k, v]) for k, v in<EOL>dict_.items()]<EOL><DEDENT>return cls(table, columns, row_columns, tab, key_on)<EOL>
:param dict_: dict of dict or dict of list :param columns: list of strings to label the columns on print out :param row_columns: list of columns in the actually data :param tab: str of the tab to use before the row on printout :param key_on: str of the column to key each row on :return: SeabornTable
f5033:c0:m2
@classmethod<EOL><INDENT>def csv_to_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>remove_empty_rows=True, key_on=None, deliminator='<STR_LIT:U+002C>',<EOL>eval_cells=True):<DEDENT>
lines = cls._get_lines(file_path, text, replace=u'<STR_LIT>')<EOL>for i in range(len(lines)):<EOL><INDENT>lines[i] = lines[i].replace('<STR_LIT:\r>', '<STR_LIT:\n>')<EOL>lines[i] = lines[i].replace('<STR_LIT>', '<STR_LIT:\r>').split('<STR_LIT:U+002C>')<EOL><DEDENT>data = cls._merge_quoted_cells(lines, deliminator, remove_empty_rows,<EOL>eval_cells)<EOL>row_columns = data[<NUM_LIT:0>]<EOL>if len(row_columns) != len(set(row_columns)): <EOL><INDENT>for i, col in enumerate(row_columns):<EOL><INDENT>count = row_columns[:i].count(col)<EOL>row_columns[i] = '<STR_LIT>' % (col, count) if count else col<EOL><DEDENT><DEDENT>return cls.list_to_obj(data[<NUM_LIT:1>:], columns=columns,<EOL>row_columns=row_columns, key_on=key_on)<EOL>
This will convert a csv file or csv text into a seaborn table and return it :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param remove_empty_rows: bool if True will remove empty rows which can happen in non-trimmed file :param key_on: list of str of columns to key on :param deliminator: str to use as a deliminator, defaults to , :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m4
@classmethod<EOL><INDENT>def grid_to_obj(cls, file_path=None, text='<STR_LIT>', edges=None,<EOL>columns=None, eval_cells=True, key_on=None):<DEDENT>
edges = edges if edges else cls.FANCY<EOL>lines = cls._get_lines(file_path, text)<EOL>data = []<EOL>for i in range(len(lines)-<NUM_LIT:1>):<EOL><INDENT>if i % <NUM_LIT:2> == <NUM_LIT:1>:<EOL><INDENT>row = lines[i].split(edges['<STR_LIT>'])[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>data.append([cls._eval_cell(r, _eval=eval_cells) for r in row])<EOL><DEDENT><DEDENT>row_columns = data[<NUM_LIT:0>]<EOL>if len(row_columns) != len(set(row_columns)): <EOL><INDENT>for i, col in enumerate(row_columns):<EOL><INDENT>count = row_columns[:i].count(col)<EOL>row_columns[i] = '<STR_LIT>' % (col, count) if count else col<EOL><DEDENT><DEDENT>return cls.list_to_obj(data[<NUM_LIT:1>:], columns=columns,<EOL>row_columns=row_columns, key_on=key_on)<EOL>
This will convert a grid file or grid text into a seaborn table and return it :param file_path: str of the path to the file :param text: str of the grid text :param columns: list of str of columns to use :param key_on: list of str of columns to key on :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m5
@classmethod<EOL><INDENT>def txt_to_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>remove_empty_rows=True, key_on=None,<EOL>row_columns=None, deliminator='<STR_LIT:\t>', eval_cells=True):<DEDENT>
return cls.str_to_obj(file_path=file_path, text=text, columns=columns,<EOL>remove_empty_rows=remove_empty_rows,<EOL>key_on=key_on, row_columns=row_columns,<EOL>deliminator=deliminator, eval_cells=eval_cells)<EOL>
This will convert text file or text to a seaborn table and return it :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param row_columns: list of str of columns in data but not to use :param remove_empty_rows: bool if True will remove empty rows :param key_on: list of str of columns to key on :param deliminator: str to use as a deliminator :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m7
@classmethod<EOL><INDENT>def str_to_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>remove_empty_rows=True, key_on=None,<EOL>row_columns=None, deliminator='<STR_LIT:\t>', eval_cells=True):<DEDENT>
text = cls._get_lines(file_path, text)<EOL>if len(text) == <NUM_LIT:1>:<EOL><INDENT>text = text[<NUM_LIT:0>].split('<STR_LIT:\r>')<EOL><DEDENT>list_of_list = [[cls._eval_cell(cell, _eval=eval_cells)<EOL>for cell in row.split(deliminator)]<EOL>for row in text if not remove_empty_rows or<EOL>True in [bool(r) for r in row]]<EOL>if list_of_list[<NUM_LIT:0>][<NUM_LIT:0>] == '<STR_LIT>' and list_of_list[<NUM_LIT:0>][-<NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>list_of_list = [row[<NUM_LIT:1>:-<NUM_LIT:1>] for row in list_of_list]<EOL><DEDENT>return cls.list_to_obj(list_of_list, key_on=key_on, columns=columns,<EOL>row_columns=row_columns)<EOL>
This will convert text file or text to a seaborn table and return it :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param row_columns: list of str of columns in data but not to use :param remove_empty_rows: bool if True will remove empty rows :param key_on: list of str of columns to key on :param deliminator: str to use as a deliminator :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m8
@classmethod<EOL><INDENT>def rst_to_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>remove_empty_rows=True, key_on=None,<EOL>deliminator='<STR_LIT:U+0020>', eval_cells=True):<DEDENT>
text = cls._get_lines(file_path, text)<EOL>if len(text) == <NUM_LIT:1>:<EOL><INDENT>text = text[<NUM_LIT:0>].split('<STR_LIT:\r>')<EOL><DEDENT>for i in [-<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:0>]:<EOL><INDENT>if not text[i].replace('<STR_LIT:=>', '<STR_LIT>').strip():<EOL><INDENT>text.pop(i) <EOL><DEDENT><DEDENT>lines = [row.split() for row in text]<EOL>list_of_list = cls._merge_quoted_cells(lines, deliminator,<EOL>remove_empty_rows, eval_cells,<EOL>excel_boolean=False)<EOL>return cls.list_to_obj(list_of_list, key_on=key_on, columns=columns)<EOL>
This will convert a rst file or text to a seaborn table :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param remove_empty_rows: bool if True will remove empty rows :param key_on: list of str of columns to key on :param deliminator: str to use as a deliminator :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m9
@classmethod<EOL><INDENT>def psql_to_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>remove_empty_rows=True, key_on=None,<EOL>deliminator='<STR_LIT>', eval_cells=True):<DEDENT>
text = cls._get_lines(file_path, text)<EOL>if len(text) == <NUM_LIT:1>:<EOL><INDENT>text = text[<NUM_LIT:0>].split('<STR_LIT:\r>')<EOL><DEDENT>if not text[<NUM_LIT:1>].replace('<STR_LIT:+>', '<STR_LIT>').replace('<STR_LIT:->', '<STR_LIT>').strip():<EOL><INDENT>text.pop(<NUM_LIT:1>) <EOL><DEDENT>list_of_list = [[cls._eval_cell(cell, _eval=eval_cells)<EOL>for cell in row.split(deliminator)]<EOL>for row in text if not remove_empty_rows or<EOL>True in [bool(r) for r in row]]<EOL>return cls.list_to_obj(list_of_list, key_on=key_on, columns=columns)<EOL>
This will convert a psql file or text to a seaborn table :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param remove_empty_rows: bool if True will remove empty rows :param key_on: list of str of columns to key on :param deliminator: str to use as a deliminator :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m10
@classmethod<EOL><INDENT>def html_to_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>key_on=None, ignore_code_blocks=True, eval_cells=True):<DEDENT>
raise NotImplemented<EOL>
This will convert a html file or text to a seaborn table :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param remove_empty_rows: bool if True will remove empty rows :param key_on: list of str of columns to key on :param deliminator: str to use as a deliminator :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m11
@classmethod<EOL><INDENT>def mark_down_to_dict_of_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>key_on=None, eval_cells=True):<DEDENT>
text = cls._get_lines(file_path, text, split_lines=False)<EOL>ret = OrderedDict()<EOL>paragraphs = text.split('<STR_LIT>')<EOL>for paragraph in paragraphs[<NUM_LIT:1>:]:<EOL><INDENT>header, text = paragraph.split('<STR_LIT:\n>', <NUM_LIT:1>)<EOL>ret[header.strip()] = cls.mark_down_to_obj(<EOL>text=text, columns=columns, key_on=key_on,<EOL>eval_cells=eval_cells)<EOL><DEDENT>return ret<EOL>
This will read multiple tables separated by a #### Header and return it as a dictionary of headers :param file_path: str of the path to the file :param text: str of the mark down text :param columns: list of str of columns to use :param key_on: list of str of columns to key on :param eval_cells: bool if True will try to evaluate numbers :return: OrderedDict of {<header>: SeabornTable}
f5033:c0:m12
@classmethod<EOL><INDENT>def md_to_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>key_on=None, ignore_code_blocks=True, eval_cells=True):<DEDENT>
return cls.mark_down_to_obj(file_path=file_path, text=text,<EOL>columns=columns, key_on=key_on,<EOL>ignore_code_blocks=ignore_code_blocks,<EOL>eval_cells=eval_cells)<EOL>
This will convert a mark down file to a seaborn table :param file_path: str of the path to the file :param text: str of the mark down text :param columns: list of str of columns to use :param key_on: list of str of columns to key on :param ignore_code_blocks: bool if true will filter out any lines between ``` :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m13
@classmethod<EOL><INDENT>def mark_down_to_obj(cls, file_path=None, text='<STR_LIT>', columns=None,<EOL>key_on=None, ignore_code_blocks=True, eval_cells=True):<DEDENT>
text = cls._get_lines(file_path, text, split_lines=False)<EOL>if ignore_code_blocks:<EOL><INDENT>text = text.split("<STR_LIT>")<EOL>for i in range(<NUM_LIT:1>, len(text), <NUM_LIT:2>):<EOL><INDENT>text.pop(i)<EOL><DEDENT>text = ('<STR_LIT>'.join(text)).strip()<EOL><DEDENT>assert text.startswith('<STR_LIT:|>') and text.endswith(<EOL>'<STR_LIT:|>'), "<STR_LIT>"<EOL>table = []<EOL>for row in text.split('<STR_LIT:\n>'):<EOL><INDENT>row = row.strip()<EOL>if row == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>assert row[<NUM_LIT:0>] == '<STR_LIT:|>' and row[-<NUM_LIT:1>] == '<STR_LIT:|>','<STR_LIT>' % row<EOL>table.append([cls._clean_cell(cell, _eval=eval_cells)<EOL>for cell in row[<NUM_LIT:1>:-<NUM_LIT:1>].split('<STR_LIT:|>')])<EOL><DEDENT>return cls(table=table[<NUM_LIT:2>:], columns=columns,<EOL>key_on=key_on, row_columns=table[<NUM_LIT:0>])<EOL>
This will convert a mark down file to a seaborn table and return it :param file_path: str of the path to the file :param text: str of the mark down text :param columns: list of str of columns to use :param key_on: list of str of columns to key on :param ignore_code_blocks: bool if true will filter out any lines between ``` :param eval_cells: bool if True will try to evaluate numbers :return: SeabornTable
f5033:c0:m14
@classmethod<EOL><INDENT>def objs_to_mark_down(cls, tables, file_path=None, keys=None,<EOL>pretty_columns=True, quote_numbers=True):<DEDENT>
keys = keys or tables.keys()<EOL>ret = ['<STR_LIT>' + key + '<STR_LIT:\n>' + tables[key].obj_to_mark_down(<EOL>pretty_columns=pretty_columns, quote_numbers=quote_numbers)<EOL>for key in keys]<EOL>ret = '<STR_LIT>'.join(ret)<EOL>cls._save_file(file_path, ret)<EOL>return ret<EOL>
This will return a str of multiple mark down tables. :param tables: dict of {str <name>:SeabornTable} :param file_path: str of the path to the file :param keys: list of str of the order of keys to use :param pretty_columns: bool if True will make the columns pretty :param quote_numbers: bool if True will quote numbers that are strings :return: str of the converted markdown tables
f5033:c0:m15
def obj_to_md(self, file_path=None, title_columns=False,<EOL>quote_numbers=True):
return self.obj_to_mark_down(file_path=file_path,<EOL>title_columns=title_columns,<EOL>quote_numbers=quote_numbers)<EOL>
This will return a str of a mark down tables. :param title_columns: bool if True will title all headers :param file_path: str of the path to the file to write to :param quote_numbers: bool if True will quote numbers that are strings :return: str
f5033:c0:m16
def obj_to_mark_down(self, file_path=None, title_columns=False,<EOL>quote_numbers=True, quote_empty_str=False):
md, column_widths = self.get_data_and_shared_column_widths(<EOL>data_kwargs=dict(quote_numbers=quote_numbers,<EOL>quote_empty_str=quote_empty_str,<EOL>title_columns=title_columns),<EOL>width_kwargs = dict(padding=<NUM_LIT:1>, pad_last_column=True))<EOL>md.insert(<NUM_LIT:1>, [u"<STR_LIT::>" + u'<STR_LIT:->' * (width - <NUM_LIT:1>) for width in column_widths])<EOL>md = [u'<STR_LIT>'.join([row[c].ljust(column_widths[c])<EOL>for c in range(len(row))]) for row in md]<EOL>ret = u'<STR_LIT>' + u'<STR_LIT>'.join(md) + u'<STR_LIT>'<EOL>self._save_file(file_path, ret)<EOL>return ret<EOL>
This will return a str of a mark down table. :param title_columns: bool if True will title all headers :param file_path: str of the path to the file to write to :param quote_numbers: bool if True will quote numbers that are strings :param quote_empty_str: bool if True will quote empty strings :return: str
f5033:c0:m17
def obj_to_txt(self, file_path=None, deliminator=None, tab=None,<EOL>quote_numbers=True, quote_empty_str=False):
return self.obj_to_str(file_path=file_path, deliminator=deliminator,<EOL>tab=tab, quote_numbers=quote_numbers,<EOL>quote_empty_str=quote_empty_str)<EOL>
This will return a simple str table. :param file_path: str of the path to the file :param keys: list of str of the order of keys to use :param tab: string of offset of the table :param quote_numbers: bool if True will quote numbers that are strings :param quote_empty_str: bool if True will quote empty strings :return: str of the converted markdown tables
f5033:c0:m18
def obj_to_str(self, file_path=None, deliminator=None, tab=None,<EOL>quote_numbers=True, quote_empty_str=False):
deliminator = self.deliminator if deliminator is Noneelse deliminator<EOL>tab = self.tab if tab is None else tab<EOL>list_of_list, column_widths = self.get_data_and_shared_column_widths(<EOL>data_kwargs=dict(quote_numbers=quote_numbers,<EOL>quote_empty_str=quote_empty_str),<EOL>width_kwargs = dict(padding=<NUM_LIT:0>))<EOL>ret = [[cell.ljust(column_widths[i]) for i, cell in enumerate(row)]<EOL>for row in list_of_list]<EOL>ret = [deliminator.join(row) for row in ret]<EOL>ret = tab + (u'<STR_LIT:\n>' + tab).join(ret)<EOL>self._save_file(file_path, ret)<EOL>return ret<EOL>
This will return a simple str table. :param file_path: str of the path to the file :param keys: list of str of the order of keys to use :param tab: string of offset of the table :param quote_numbers: bool if True will quote numbers that are strings :param quote_empty_str: bool if True will quote empty strings :return: str of the converted markdown tables
f5033:c0:m19