signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def add_depths(events):
depth = <NUM_LIT:0><EOL>for event in events:<EOL><INDENT>if is_exception(event):<EOL><INDENT>yield event<EOL><DEDENT>else:<EOL><INDENT>if event.event_type == IonEventType.CONTAINER_END:<EOL><INDENT>depth -= <NUM_LIT:1><EOL><DEDENT>if event.event_type.is_stream_signal:<EOL><INDENT>yield event<EOL><DEDENT>else:<EOL><INDENT>yield event.derive_depth(depth)<EOL><DEDENT>if event.event_type == IonEventType.CONTAINER_START:<EOL><INDENT>depth += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>
Adds the appropriate depths to an iterable of :class:`IonEvent`.
f4989:m0
def value_iter(event_func, values, *args):
for seq in values:<EOL><INDENT>data = seq[<NUM_LIT:0>]<EOL>event_pairs = list(event_func(data, seq[<NUM_LIT:1>:], *args))<EOL>yield data, event_pairs<EOL><DEDENT>
Generates input/output event pairs from a sequence whose first element is the raw data and the following elements are the expected output events.
f4989:m2
def listify(iter_func):
def delegate(*args, **kwargs):<EOL><INDENT>return list(iter_func(*args, **kwargs))<EOL><DEDENT>delegate.__name__ = iter_func.__name__<EOL>return delegate<EOL>
Takes an iterator function and returns a function that materializes it into a list.
f4990:m0
@contextmanager<EOL>def noop_manager():
yield<EOL>
A no-op context manager
f4990:m1
def is_exception(val):
return isinstance(val, type) and issubclass(val, Exception)<EOL>
Returns whether a given value is an exception type (not an instance).
f4990:m2
def parametrize(*values):
values = tuple((value,) for value in values)<EOL>def decorator(func):<EOL><INDENT>if func.__code__.co_argcount != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>argname = func.__code__.co_varnames[<NUM_LIT:0>]<EOL>real_decorator = pytest.mark.parametrize(<EOL>argnames=[argname],<EOL>argvalues=values,<EOL>ids=lambda x: str(x).replace('<STR_LIT:.>', '<STR_LIT:_>')<EOL>)<EOL>return real_decorator(func)<EOL><DEDENT>return decorator<EOL>
Idiomatic test parametrization. Parametrizes single parameter testing functions. The assumption is that the function decorated uses something like a ``namedtuple`` as its sole argument. Makes the ``id`` string be based on the parameter value's ``__str__`` method. Examples: Usage of this decorator typically looks something like:: class _P(namedtuple('Params', 'a, b, c')): def __str__(self): return '{p.a} - {p.b} - {p.c}'.format(p=self) @tests.parametrize( _P(a='something', b=6, c=True), _P(s='some-other-thing', b=7, c=False), _P('look ma, positional', 9, True) def my_test(p): assert isinstance(p.a, str) assert p.b > 0 assert isinstance(p.c, bool) :func:`amazon.ion.util.record` is also appropriate for the parameter class/tuple:: class _P(amazon.ion.util.record('a', 'b', 'c')): def __str__(self): return '{p.a} - {p.b} - {p.c}'.format(p=self) Args: values (Sequence[Any]): A sequence of values to pass to a single argument function. Returns: pytest.mark.parametrize: The decorator.
f4990:m3
def _gen_type_len(tid, length):
type_code = tid << <NUM_LIT:4><EOL>if length < <NUM_LIT>:<EOL><INDENT>return int2byte(type_code | length)<EOL><DEDENT>else:<EOL><INDENT>type_code |= <NUM_LIT><EOL>if length <= <NUM_LIT>:<EOL><INDENT>return int2byte(type_code) + int2byte(<NUM_LIT> | length)<EOL><DEDENT><DEDENT>raise ValueError('<STR_LIT>')<EOL>
Very primitive type length encoder.
f4996:m3
def _top_level_value_params():
for data, event_pairs in _top_level_iter():<EOL><INDENT>_, first = event_pairs[<NUM_LIT:0>]<EOL>yield _P(<EOL>desc='<STR_LIT>' %(first.event_type.name, first.ion_type.name, first.value),<EOL>event_pairs=[(NEXT, END)] + event_pairs + [(NEXT, END)],<EOL>)<EOL><DEDENT>
Converts the top-level tuple list into parameters with appropriate ``NEXT`` inputs. The expectation is starting from an end of stream top-level context.
f4996:m4
def _annotate_params(params):
for param in params:<EOL><INDENT>@listify<EOL>def annotated():<EOL><INDENT>for input_event, output_event in param.event_pairs:<EOL><INDENT>if input_event.type is ReadEventType.DATA:<EOL><INDENT>data_len = _TEST_ANNOTATION_LEN + len(input_event.data)<EOL>data = _gen_type_len(_TypeID.ANNOTATION, data_len)+ _TEST_ANNOTATION_DATA+ input_event.data<EOL>input_event = read_data_event(data)<EOL>output_event = output_event.derive_annotations(_TEST_ANNOTATION_SIDS)<EOL><DEDENT>yield input_event, output_event<EOL><DEDENT><DEDENT>yield _P(<EOL>desc='<STR_LIT>' % param.desc,<EOL>event_pairs=annotated(),<EOL>)<EOL><DEDENT>
Adds annotation wrappers for a given iterator of parameters, The requirement is that the given parameters completely encapsulate a single value.
f4996:m5
def _containerize_params(params, with_skip=True):
rnd = Random()<EOL>rnd.seed(<NUM_LIT>)<EOL>params = list(params)<EOL>for param in params:<EOL><INDENT>data_len = _data_event_len(param.event_pairs)<EOL>for tid in _CONTAINER_TIDS:<EOL><INDENT>ion_type = _TID_VALUE_TYPE_TABLE[tid]<EOL>field_data = b'<STR_LIT>'<EOL>field_tok = None<EOL>field_desc = '<STR_LIT>'<EOL>if ion_type is IonType.STRUCT:<EOL><INDENT>field_sid = rnd.randint(<NUM_LIT:0>, <NUM_LIT>)<EOL>field_data = int2byte(field_sid | <NUM_LIT>)<EOL>field_tok = SymbolToken(None, field_sid)<EOL>field_desc = '<STR_LIT>' % field_sid<EOL><DEDENT>@listify<EOL>def add_field_names(event_pairs):<EOL><INDENT>first = True<EOL>for read_event, ion_event in event_pairs:<EOL><INDENT>if first and not ion_event.event_type.is_stream_signal:<EOL><INDENT>ion_event = ion_event.derive_field_name(field_tok)<EOL>first = False<EOL><DEDENT>yield read_event, ion_event<EOL><DEDENT><DEDENT>type_header = _gen_type_len(tid, data_len + len(field_data)) + field_data<EOL>start = [<EOL>(NEXT, END),<EOL>(e_read(type_header), e_start(ion_type)),<EOL>(NEXT, INC)<EOL>]<EOL>mid = add_field_names(param.event_pairs[<NUM_LIT:1>:-<NUM_LIT:1>])<EOL>end = [(NEXT, e_end(ion_type)), (NEXT, END)]<EOL>desc = '<STR_LIT>' % (ion_type.name, field_desc, param.desc)<EOL>yield _P(<EOL>desc=desc,<EOL>event_pairs=start + mid + end,<EOL>)<EOL>if with_skip:<EOL><INDENT>@listify<EOL>def only_data_inc(event_pairs):<EOL><INDENT>for read_event, ion_event in event_pairs:<EOL><INDENT>if read_event.type is ReadEventType.DATA:<EOL><INDENT>yield read_event, INC<EOL><DEDENT><DEDENT><DEDENT>start = start[:-<NUM_LIT:1>] + [(SKIP, INC)]<EOL>end = only_data_inc(param.event_pairs)<EOL>end = end[:-<NUM_LIT:1>] + [(end[-<NUM_LIT:1>][<NUM_LIT:0>], e_end(ion_type)), (NEXT, END)]<EOL>yield _P(<EOL>desc='<STR_LIT>' % desc,<EOL>event_pairs=start + end,<EOL>)<EOL><DEDENT><DEDENT><DEDENT>
Adds container wrappers for a given iteration of parameters. The requirement is that each parameter is a self-contained single value.
f4996:m7
def _generate_annotations():
i = <NUM_LIT:0><EOL>while True:<EOL><INDENT>yield _TEST_ANNOTATIONS[i]<EOL>i += <NUM_LIT:1><EOL>if i == len(_TEST_ANNOTATIONS):<EOL><INDENT>i = <NUM_LIT:0><EOL><DEDENT><DEDENT>
Circularly generates sequences of test annotations. The annotations sequence yielded from this generator must never be equivalent to the annotations sequence last yielded by this generator.
f4997:m4
def record(*fields):
@six.add_metaclass(_RecordMetaClass)<EOL>class RecordType(object):<EOL><INDENT>_record_sentinel = True<EOL>_record_fields = fields<EOL><DEDENT>return RecordType<EOL>
Constructs a type that can be extended to create immutable, value types. Examples: A typical declaration looks like:: class MyRecord(record('a', ('b', 1))): pass The above would make a sub-class of ``collections.namedtuple`` that was named ``MyRecord`` with a constructor that had the ``b`` field set to 1 by default. Note: This uses meta-class machinery to rewrite the inheritance hierarchy. This is done in order to make sure that the underlying ``namedtuple`` instance is bound to the right type name and to make sure that the synthetic class that is generated to enable this machinery is not enabled for sub-classes of a user's record class. Args: fields (list[str | (str, any)]): A sequence of str or pairs that
f5004:m0
def coroutine(func):
def wrapper(*args, **kwargs):<EOL><INDENT>gen = func(*args, **kwargs)<EOL>val = next(gen)<EOL>if val != None:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>return gen<EOL><DEDENT>wrapper.__name__ = func.__name__<EOL>wrapper.__doc__ = func.__doc__<EOL>return wrapper<EOL>
Wraps a PEP-342 enhanced generator in a way that avoids boilerplate of the "priming" call to ``next``. Args: func (Callable): The function constructing a generator to decorate. Returns: Callable: The decorated generator.
f5004:m1
def unicode_iter(val):
val_iter = iter(val)<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>code_point = next(_next_code_point(val, val_iter, to_int=ord))<EOL><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT>if code_point is None:<EOL><INDENT>raise ValueError('<STR_LIT>' % val)<EOL><DEDENT>yield code_point<EOL><DEDENT>
Provides an iterator over the *code points* of the given Unicode sequence. Notes: Before PEP-393, Python has the potential to support Unicode as UTF-16 or UTF-32. This is reified in the property as ``sys.maxunicode``. As a result, naive iteration of Unicode sequences will render non-character code points such as UTF-16 surrogates. Args: val (unicode): The unicode sequence to iterate over as integer code points in the range ``0x0`` to ``0x10FFFF``.
f5004:m2
def _next_code_point(val, val_iter, yield_char=False, to_int=lambda x: x):
try:<EOL><INDENT>high = next(val_iter)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT>low = None<EOL>code_point = to_int(high)<EOL>if _LOW_SURROGATE_START <= code_point <= _LOW_SURROGATE_END:<EOL><INDENT>raise ValueError('<STR_LIT>' % code_point)<EOL><DEDENT>elif _HIGH_SURROGATE_START <= code_point <= _HIGH_SURROGATE_END:<EOL><INDENT>def combine_surrogates():<EOL><INDENT>low_surrogate = next(val_iter)<EOL>low_code_point = to_int(low_surrogate)<EOL>if low_code_point < _LOW_SURROGATE_START or low_code_point > _LOW_SURROGATE_END:<EOL><INDENT>raise ValueError('<STR_LIT>' % code_point)<EOL><DEDENT>real_code_point = _NON_BMP_OFFSET<EOL>real_code_point += (code_point - _HIGH_SURROGATE_START) << <NUM_LIT:10><EOL>real_code_point += (low_code_point - _LOW_SURROGATE_START)<EOL>return real_code_point, low_surrogate<EOL><DEDENT>try:<EOL><INDENT>code_point, low = combine_surrogates()<EOL><DEDENT>except StopIteration:<EOL><INDENT>yield None<EOL>val_iter = iter(val) <EOL>code_point, low = combine_surrogates()<EOL><DEDENT><DEDENT>if yield_char and low is not None:<EOL><INDENT>out = CodePoint(code_point)<EOL>if isinstance(val, six.text_type):<EOL><INDENT>out.char = high + low<EOL><DEDENT>else:<EOL><INDENT>out.char = six.unichr(high) + six.unichr(low)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>out = code_point<EOL><DEDENT>yield out<EOL>
Provides the next *code point* in the given Unicode sequence. This generator function yields complete character code points, never incomplete surrogates. When a low surrogate is found without following a high surrogate, this function raises ``ValueError`` for having encountered an unpaired low surrogate. When the provided iterator ends on a high surrogate, this function yields ``None``. This is the **only** case in which this function yields ``None``. When this occurs, the user may append additional data to the input unicode sequence and resume iterating through another ``next`` on this generator. When this function receives ``next`` after yielding ``None``, it *reinitializes the unicode iterator*. This means that this feature can only be used for values that contain an ``__iter__`` implementation that remains at the current position in the data when called (e.g. :class:`BufferQueue`). At this point, there are only two possible outcomes: * If next code point is a valid low surrogate, this function yields the combined code point represented by the surrogate pair. * Otherwise, this function raises ``ValueError`` for having encountered an unpaired high surrogate. Args: val (unicode|BufferQueue): A unicode sequence or unicode BufferQueue over which to iterate. val_iter (Iterator[unicode|BufferQueue]): The unicode sequence iterator over ``val`` from which to generate the next integer code point in the range ``0x0`` to ``0x10FFFF``. yield_char (Optional[bool]): If True **and** the character code point resulted from a surrogate pair, this function will yield a :class:`CodePoint` representing the character code point and containing the original unicode character. This is useful when the original unicode character will be needed again because UCS2 Python builds will error when trying to convert code points greater than 0xFFFF back into their unicode character representations. This avoids requiring the user to mathematically re-derive the surrogate pair in order to successfully convert the code point back to a unicode character. to_int (Optional[callable]): A function to call on each element of val_iter to convert that element to an int.
f5004:m3
def __getitem__(cls, name):
return cls._enum_members[name]<EOL>
Looks up an enumeration value field by integer value.
f5004:c0:m1
def __iter__(self):
return six.itervalues(self._enum_members)<EOL>
Iterates through the values of the enumeration in no specific order.
f5004:c0:m2
def dump(obj, fp, imports=None, binary=True, sequence_as_stream=False, skipkeys=False, ensure_ascii=True,<EOL>check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='<STR_LIT:utf-8>', default=None,<EOL>use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False,<EOL>item_sort_key=None, for_json=None, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False,<EOL>**kw):
raw_writer = binary_writer(imports) if binary else text_writer(indent=indent)<EOL>writer = blocking_writer(raw_writer, fp)<EOL>writer.send(ION_VERSION_MARKER_EVENT) <EOL>if sequence_as_stream and isinstance(obj, (list, tuple)):<EOL><INDENT>for top_level in obj:<EOL><INDENT>_dump(top_level, writer)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_dump(obj, writer)<EOL><DEDENT>writer.send(ION_STREAM_END_EVENT)<EOL>
Serialize ``obj`` as an Ion-formatted stream to ``fp`` (a file-like object), using the following conversion table:: +-------------------+-------------------+ | Python | Ion | |-------------------+-------------------| | None | null.null | |-------------------+-------------------| | IonPyNull(<type>) | null.<type> | |-------------------+-------------------| | True, False, | | | IonPyInt(BOOL), | bool | | IonPyBool, | | |-------------------+-------------------| | int (Python 2, 3) | | | long (Python 2), | int | | IonPyInt(INT) | | |-------------------+-------------------| | float, IonPyFloat | float | |-------------------+-------------------| | Decimal, | | | IonPyDecimal | decimal | |-------------------+-------------------| | datetime, | | | Timestamp, | timestamp | | IonPyTimestamp | | |-------------------+-------------------| | SymbolToken, | | | IonPySymbol, | symbol | | IonPyText(SYMBOL) | | |-------------------+-------------------| | str (Python 3), | | | unicode (Python2),| string | | IonPyText(STRING) | | |-------------------+-------------------| | IonPyBytes(CLOB) | clob | |-------------------+-------------------| | str (Python 2), | | | bytes (Python 3) | blob | | IonPyBytes(BLOB) | | |-------------------+-------------------| | list, tuple, | | | IonPyList(LIST) | list | |-------------------+-------------------| | IonPyList(SEXP) | sexp | |-------------------+-------------------| | dict, namedtuple, | | | IonPyDict | struct | +-------------------+-------------------+ Args: obj (Any): A python object to serialize according to the above table. Any Python object which is neither an instance of nor inherits from one of the types in the above table will raise TypeError. fp (BaseIO): A file-like object. imports (Optional[Sequence[SymbolTable]]): A sequence of shared symbol tables to be used by by the writer. binary (Optional[True|False]): When True, outputs binary Ion. When false, outputs text Ion. sequence_as_stream (Optional[True|False]): When True, if ``obj`` is a sequence, it will be treated as a stream of top-level Ion values (i.e. the resulting Ion data will begin with ``obj``'s first element). Default: False. skipkeys: NOT IMPLEMENTED ensure_ascii: NOT IMPLEMENTED check_circular: NOT IMPLEMENTED allow_nan: NOT IMPLEMENTED cls: NOT IMPLEMENTED indent (Str): If binary is False and indent is a string, then members of containers will be pretty-printed with a newline followed by that string repeated for each level of nesting. None (the default) selects the most compact representation without any newlines. Example: to indent with four spaces per level of nesting, use ``' '``. separators: NOT IMPLEMENTED encoding: NOT IMPLEMENTED default: NOT IMPLEMENTED use_decimal: NOT IMPLEMENTED namedtuple_as_object: NOT IMPLEMENTED tuple_as_array: NOT IMPLEMENTED bigint_as_string: NOT IMPLEMENTED sort_keys: NOT IMPLEMENTED item_sort_key: NOT IMPLEMENTED for_json: NOT IMPLEMENTED ignore_nan: NOT IMPLEMENTED int_as_string_bitcount: NOT IMPLEMENTED iterable_as_array: NOT IMPLEMENTED **kw: NOT IMPLEMENTED
f5005:m0
def dumps(obj, imports=None, binary=True, sequence_as_stream=False, skipkeys=False, ensure_ascii=True, check_circular=True,<EOL>allow_nan=True, cls=None, indent=None, separators=None, encoding='<STR_LIT:utf-8>', default=None, use_decimal=True,<EOL>namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None,<EOL>for_json=None, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw):
ion_buffer = six.BytesIO()<EOL>dump(obj, ion_buffer, sequence_as_stream=sequence_as_stream, binary=binary, skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular,<EOL>allow_nan=allow_nan, cls=cls, indent=indent, separators=separators, encoding=encoding, default=default,<EOL>use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array,<EOL>bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json,<EOL>ignore_nan=ignore_nan, int_as_string_bitcount=int_as_string_bitcount, iterable_as_array=iterable_as_array)<EOL>ret_val = ion_buffer.getvalue()<EOL>ion_buffer.close()<EOL>if not binary:<EOL><INDENT>ret_val = ret_val.decode('<STR_LIT:utf-8>')<EOL><DEDENT>return ret_val<EOL>
Serialize ``obj`` as Python ``string`` or ``bytes`` object, using the conversion table used by ``dump`` (above). Args: obj (Any): A python object to serialize according to the above table. Any Python object which is neither an instance of nor inherits from one of the types in the above table will raise TypeError. imports (Optional[Sequence[SymbolTable]]): A sequence of shared symbol tables to be used by by the writer. binary (Optional[True|False]): When True, outputs binary Ion. When false, outputs text Ion. sequence_as_stream (Optional[True|False]): When True, if ``obj`` is a sequence, it will be treated as a stream of top-level Ion values (i.e. the resulting Ion data will begin with ``obj``'s first element). Default: False. skipkeys: NOT IMPLEMENTED ensure_ascii: NOT IMPLEMENTED check_circular: NOT IMPLEMENTED allow_nan: NOT IMPLEMENTED cls: NOT IMPLEMENTED indent (Str): If binary is False and indent is a string, then members of containers will be pretty-printed with a newline followed by that string repeated for each level of nesting. None (the default) selects the most compact representation without any newlines. Example: to indent with four spaces per level of nesting, use ``' '``. separators: NOT IMPLEMENTED encoding: NOT IMPLEMENTED default: NOT IMPLEMENTED use_decimal: NOT IMPLEMENTED namedtuple_as_object: NOT IMPLEMENTED tuple_as_array: NOT IMPLEMENTED bigint_as_string: NOT IMPLEMENTED sort_keys: NOT IMPLEMENTED item_sort_key: NOT IMPLEMENTED for_json: NOT IMPLEMENTED ignore_nan: NOT IMPLEMENTED int_as_string_bitcount: NOT IMPLEMENTED iterable_as_array: NOT IMPLEMENTED **kw: NOT IMPLEMENTED Returns: Union[str|bytes]: The string or binary representation of the data. if ``binary=True``, this will be a ``bytes`` object, otherwise this will be a ``str`` object (or ``unicode`` in the case of Python 2.x)
f5005:m3
def load(fp, catalog=None, single_value=True, encoding='<STR_LIT:utf-8>', cls=None, object_hook=None, parse_float=None,<EOL>parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=None, **kw):
if isinstance(fp, _TEXT_TYPES):<EOL><INDENT>raw_reader = text_reader(is_unicode=True)<EOL><DEDENT>else:<EOL><INDENT>maybe_ivm = fp.read(<NUM_LIT:4>)<EOL>fp.seek(<NUM_LIT:0>)<EOL>if maybe_ivm == _IVM:<EOL><INDENT>raw_reader = binary_reader()<EOL><DEDENT>else:<EOL><INDENT>raw_reader = text_reader()<EOL><DEDENT><DEDENT>reader = blocking_reader(managed_reader(raw_reader, catalog), fp)<EOL>out = [] <EOL>_load(out, reader)<EOL>if single_value:<EOL><INDENT>if len(out) != <NUM_LIT:1>:<EOL><INDENT>raise IonException('<STR_LIT>' % (len(out),))<EOL><DEDENT>return out[<NUM_LIT:0>]<EOL><DEDENT>return out<EOL>
Deserialize ``fp`` (a file-like object), which contains a text or binary Ion stream, to a Python object using the following conversion table:: +-------------------+-------------------+ | Ion | Python | |-------------------+-------------------| | null.<type> | IonPyNull(<type>) | |-------------------+-------------------| | bool | IonPyBool | |-------------------+-------------------| | int | IonPyInt | |-------------------+-------------------| | float | IonPyFloat | |-------------------+-------------------| | decimal | IonPyDecimal | |-------------------+-------------------| | timestamp | IonPyTimestamp | |-------------------+-------------------| | symbol | IonPySymbol | |-------------------+-------------------| | string | IonPyText(STRING) | |-------------------+-------------------| | clob | IonPyBytes(CLOB) | |-------------------+-------------------| | blob | IonPyBytes(BLOB) | |-------------------+-------------------| | list | IonPyList(LIST) | |-------------------+-------------------| | sexp | IonPyList(SEXP) | |-------------------+-------------------| | struct | IonPyDict | +-------------------+-------------------+ Args: fp (BaseIO): A file-like object containing Ion data. catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving symbol table imports. single_value (Optional[True|False]): When True, the data in ``obj`` is interpreted as a single Ion value, and will be returned without an enclosing container. If True and there are multiple top-level values in the Ion stream, IonException will be raised. NOTE: this means that when data is dumped using ``sequence_as_stream=True``, it must be loaded using ``single_value=False``. Default: True. encoding: NOT IMPLEMENTED cls: NOT IMPLEMENTED object_hook: NOT IMPLEMENTED parse_float: NOT IMPLEMENTED parse_int: NOT IMPLEMENTED parse_constant: NOT IMPLEMENTED object_pairs_hook: NOT IMPLEMENTED use_decimal: NOT IMPLEMENTED **kw: NOT IMPLEMENTED Returns (Any): if single_value is True: A Python object representing a single Ion value. else: A sequence of Python objects representing a stream of Ion values.
f5005:m4
def loads(ion_str, catalog=None, single_value=True, encoding='<STR_LIT:utf-8>', cls=None, object_hook=None, parse_float=None,<EOL>parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=None, **kw):
if isinstance(ion_str, six.binary_type):<EOL><INDENT>ion_buffer = BytesIO(ion_str)<EOL><DEDENT>elif isinstance(ion_str, six.text_type):<EOL><INDENT>ion_buffer = six.StringIO(ion_str)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % ion_str)<EOL><DEDENT>return load(ion_buffer, catalog=catalog, single_value=single_value, encoding=encoding, cls=cls,<EOL>object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant,<EOL>object_pairs_hook=object_pairs_hook, use_decimal=use_decimal)<EOL>
Deserialize ``ion_str``, which is a string representation of an Ion object, to a Python object using the conversion table used by load (above). Args: fp (str): A string representation of Ion data. catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving symbol table imports. single_value (Optional[True|False]): When True, the data in ``ion_str`` is interpreted as a single Ion value, and will be returned without an enclosing container. If True and there are multiple top-level values in the Ion stream, IonException will be raised. NOTE: this means that when data is dumped using ``sequence_as_stream=True``, it must be loaded using ``single_value=False``. Default: True. encoding: NOT IMPLEMENTED cls: NOT IMPLEMENTED object_hook: NOT IMPLEMENTED parse_float: NOT IMPLEMENTED parse_int: NOT IMPLEMENTED parse_constant: NOT IMPLEMENTED object_pairs_hook: NOT IMPLEMENTED use_decimal: NOT IMPLEMENTED **kw: NOT IMPLEMENTED Returns (Any): if single_value is True: A Python object representing a single Ion value. else: A sequence of Python objects representing a stream of Ion values.
f5005:m6
def ion_equals(a, b, timestamps_instants_only=False):
if timestamps_instants_only:<EOL><INDENT>return _ion_equals_timestamps_instants(a, b)<EOL><DEDENT>return _ion_equals_timestamps_data_model(a, b)<EOL>
Tests two objects for equivalence under the Ion data model. There are three important cases: * When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the values of both operands are equivalent under the Ion data model. * When only one of the operands specifies its `ion_type` and `annotations`, this method will only return True when that operand has no annotations and has a value equivalent to the other operand under the Ion data model. * When both operands specify `ion_type` and `annotations`, this method will only return True when the ion_type and annotations of both are the same and their values are equivalent under the Ion data model. Note that the order of the operands does not matter. Args: a (object): The first operand. b (object): The second operand. timestamps_instants_only (Optional[bool]): False if timestamp objects (datetime and its subclasses) should be compared according to the Ion data model (where the instant, precision, and offset must be equal); True if these objects should be considered equivalent if they simply represent the same instant.
f5006:m0
def _ion_equals(a, b, timestamp_comparison_func, recursive_comparison_func):
for a, b in ((a, b), (b, a)): <EOL><INDENT>if isinstance(a, _IonNature):<EOL><INDENT>if isinstance(b, _IonNature):<EOL><INDENT>eq = a.ion_type is b.ion_type and _annotations_eq(a, b)<EOL><DEDENT>else:<EOL><INDENT>eq = not a.ion_annotations<EOL><DEDENT>if eq:<EOL><INDENT>if isinstance(a, IonPyList):<EOL><INDENT>return _sequences_eq(a, b, recursive_comparison_func)<EOL><DEDENT>elif isinstance(a, IonPyDict):<EOL><INDENT>return _structs_eq(a, b, recursive_comparison_func)<EOL><DEDENT>elif isinstance(a, IonPyTimestamp):<EOL><INDENT>return timestamp_comparison_func(a, b)<EOL><DEDENT>elif isinstance(a, IonPyNull):<EOL><INDENT>return isinstance(b, IonPyNull) or (b is None and a.ion_type is IonType.NULL)<EOL><DEDENT>elif isinstance(a, IonPySymbol) or (isinstance(a, IonPyText) and a.ion_type is IonType.SYMBOL):<EOL><INDENT>return _symbols_eq(a, b)<EOL><DEDENT>elif isinstance(a, IonPyDecimal):<EOL><INDENT>return _decimals_eq(a, b)<EOL><DEDENT>elif isinstance(a, IonPyFloat):<EOL><INDENT>return _floats_eq(a, b)<EOL><DEDENT>else:<EOL><INDENT>return a == b<EOL><DEDENT><DEDENT>return False<EOL><DEDENT><DEDENT>for a, b in ((a, b), (b, a)): <EOL><INDENT>if isinstance(a, list):<EOL><INDENT>return _sequences_eq(a, b, recursive_comparison_func)<EOL><DEDENT>elif isinstance(a, dict):<EOL><INDENT>return _structs_eq(a, b, recursive_comparison_func)<EOL><DEDENT>elif isinstance(a, datetime):<EOL><INDENT>return timestamp_comparison_func(a, b)<EOL><DEDENT>elif isinstance(a, SymbolToken):<EOL><INDENT>return _symbols_eq(a, b)<EOL><DEDENT>elif isinstance(a, Decimal):<EOL><INDENT>return _decimals_eq(a, b)<EOL><DEDENT>elif isinstance(a, float):<EOL><INDENT>return _floats_eq(a, b)<EOL><DEDENT><DEDENT>return a == b<EOL>
Compares a and b according to the description of the ion_equals method.
f5006:m3
def _timestamps_eq(a, b):
assert isinstance(a, datetime)<EOL>if not isinstance(b, datetime):<EOL><INDENT>return False<EOL><DEDENT>if (a.tzinfo is None) ^ (b.tzinfo is None):<EOL><INDENT>return False<EOL><DEDENT>if a.utcoffset() != b.utcoffset():<EOL><INDENT>return False<EOL><DEDENT>for a, b in ((a, b), (b, a)):<EOL><INDENT>if isinstance(a, Timestamp):<EOL><INDENT>if isinstance(b, Timestamp):<EOL><INDENT>if a.precision is b.precision and a.fractional_precision is b.fractional_precision:<EOL><INDENT>break<EOL><DEDENT>return False<EOL><DEDENT>elif a.precision is not TimestampPrecision.SECOND or a.fractional_precision != MICROSECOND_PRECISION:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return a == b<EOL>
Compares two timestamp operands for equivalence under the Ion data model.
f5006:m7
def _timestamp_instants_eq(a, b):
assert isinstance(a, datetime)<EOL>if not isinstance(b, datetime):<EOL><INDENT>return False<EOL><DEDENT>if a.tzinfo is None:<EOL><INDENT>a = a.replace(tzinfo=OffsetTZInfo())<EOL><DEDENT>if b.tzinfo is None:<EOL><INDENT>b = b.replace(tzinfo=OffsetTZInfo())<EOL><DEDENT>return a == b<EOL>
Compares two timestamp operands for point-in-time equivalence only.
f5006:m8
def _system_symbol_token(text, sid):
return SymbolToken(text, sid, ImportLocation(TEXT_ION, sid))<EOL>
Defines an Ion 1.0 system symbol token.
f5007:m0
def local_symbol_table(imports=None, symbols=()):
return SymbolTable(<EOL>table_type=LOCAL_TABLE_TYPE,<EOL>symbols=symbols,<EOL>imports=imports<EOL>)<EOL>
Constructs a local symbol table. Args: imports (Optional[SymbolTable]): Shared symbol tables to import. symbols (Optional[Iterable[Unicode]]): Initial local symbols to add. Returns: SymbolTable: A mutable local symbol table with the seeded local symbols.
f5007:m1
def shared_symbol_table(name, version, symbols, imports=None):
return SymbolTable(<EOL>table_type=SHARED_TABLE_TYPE,<EOL>symbols=symbols,<EOL>name=name,<EOL>version=version,<EOL>imports=imports<EOL>)<EOL>
Constructs a shared symbol table. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. symbols (Iterable[unicode]): The symbols to associate with the table. imports (Optional[Iterable[SymbolTable]): The shared symbol tables to inject into this one. Returns: SymbolTable: The constructed table.
f5007:m2
def placeholder_symbol_table(name, version, max_id):
if version <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % version)<EOL><DEDENT>if max_id < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % max_id)<EOL><DEDENT>return SymbolTable(<EOL>table_type=SHARED_TABLE_TYPE,<EOL>symbols=repeat(None, max_id),<EOL>name=name,<EOL>version=version,<EOL>is_substitute=True<EOL>)<EOL>
Constructs a shared symbol table that consists symbols that all have no known text. This is generally used for cases where a shared symbol table is not available by the application. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. max_id (int): The maximum ID allocated by this symbol table, must be ``>= 0`` Returns: SymbolTable: The synthesized table.
f5007:m3
def substitute_symbol_table(table, version, max_id):
if not table.table_type.is_shared:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if version <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % version)<EOL><DEDENT>if max_id < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % max_id)<EOL><DEDENT>if max_id <= table.max_id:<EOL><INDENT>symbols = (token.text for token in islice(table, max_id))<EOL><DEDENT>else:<EOL><INDENT>symbols = chain(<EOL>(token.text for token in table),<EOL>repeat(None, max_id - table.max_id)<EOL>)<EOL><DEDENT>return SymbolTable(<EOL>table_type=SHARED_TABLE_TYPE,<EOL>symbols=symbols,<EOL>name=table.name,<EOL>version=version,<EOL>is_substitute=True<EOL>)<EOL>
Substitutes a given shared symbol table for another version. * If the given table has **more** symbols than the requested substitute, then the generated symbol table will be a subset of the given table. * If the given table has **less** symbols than the requested substitute, then the generated symbol table will have symbols with unknown text generated for the difference. Args: table (SymbolTable): The shared table to derive from. version (int): The version to target. max_id (int): The maximum ID allocated by the substitute, must be ``>= 0``. Returns: SymbolTable: The synthesized table.
f5007:m4
def __import_location(self, sid):
return ImportLocation(self.name, sid)<EOL>
Returns a location for this table's SID. Only meaningful for shared tables.
f5007:c3:m1
def __new_sid(self):
self.max_id += <NUM_LIT:1><EOL>sid = self.max_id<EOL>return sid<EOL>
Allocates a new local SID.
f5007:c3:m2
def __add(self, token):
self.__symbols.append(token)<EOL>text = token.text<EOL>if text is not None and text not in self.__mapping:<EOL><INDENT>self.__mapping[text] = token<EOL><DEDENT>
Unconditionally adds a token to the table.
f5007:c3:m3
def __add_shared(self, original_token):
sid = self.__new_sid()<EOL>token = SymbolToken(original_token.text, sid, self.__import_location(sid))<EOL>self.__add(token)<EOL>return token<EOL>
Adds a token, normalizing the SID and import reference to this table.
f5007:c3:m4
def __add_import(self, original_token):
sid = self.__new_sid()<EOL>token = SymbolToken(original_token.text, sid, original_token.location)<EOL>self.__add(token)<EOL>return token<EOL>
Adds a token, normalizing only the SID
f5007:c3:m5
def __add_text(self, text):
if text is not None and not isinstance(text, six.text_type):<EOL><INDENT>raise TypeError('<STR_LIT>' % text)<EOL><DEDENT>sid = self.__new_sid()<EOL>location = None<EOL>if self.table_type.is_shared:<EOL><INDENT>location = self.__import_location(sid)<EOL><DEDENT>token = SymbolToken(text, sid, location)<EOL>self.__add(token)<EOL>return token<EOL>
Adds the given Unicode text as a locally defined symbol.
f5007:c3:m6
def intern(self, text):
if self.table_type.is_shared:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not isinstance(text, six.text_type):<EOL><INDENT>raise TypeError('<STR_LIT>' % text)<EOL><DEDENT>token = self.get(text)<EOL>if token is None:<EOL><INDENT>token = self.__add_text(text)<EOL><DEDENT>return token<EOL>
Interns the given Unicode sequence into the symbol table. Note: This operation is only valid on local symbol tables. Args: text (unicode): The target to intern. Returns: SymbolToken: The mapped symbol token which may already exist in the table.
f5007:c3:m7
def get(self, key, default=None):
if isinstance(key, six.text_type):<EOL><INDENT>return self.__mapping.get(key, None)<EOL><DEDENT>if not isinstance(key, int):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if key == <NUM_LIT:0>:<EOL><INDENT>return SYMBOL_ZERO_TOKEN<EOL><DEDENT>index = key - <NUM_LIT:1><EOL>if index < <NUM_LIT:0> or key > len(self):<EOL><INDENT>return default<EOL><DEDENT>return self.__symbols[index]<EOL>
Returns a token by text or local ID, with a default. A given text image may be associated with more than one symbol ID. This will return the first definition. Note: User defined symbol IDs are always one-based. Symbol zero is a special symbol that always has no text. Args: key (unicode | int): The key to lookup. default(Optional[SymbolToken]): The default to return if the key is not found Returns: SymbolToken: The token associated with the key or the default if it doesn't exist.
f5007:c3:m8
def __getitem__(self, key):
token = self.get(key)<EOL>if token is None:<EOL><INDENT>raise KeyError('<STR_LIT>' % key)<EOL><DEDENT>return token<EOL>
Returns a token by text or local ID. Args: key (unicode | int): The text or ID to lookup. Returns: SymbolToken: The token associated with the key. Raises: KeyError: If the key is not in the table. See Also: :meth:`get()`
f5007:c3:m9
def __len__(self):
return len(self.__symbols)<EOL>
Returns the number of symbols within the table.
f5007:c3:m10
def __iter__(self):
return iter(self.__symbols)<EOL>
Iterator over the table's tokens. Returns: Iterable[SymbolToken]: The tokens in this table in defined order.
f5007:c3:m11
def __eq__(self, other):
if self is other:<EOL><INDENT>return True<EOL><DEDENT>if self.table_type != getattr(other, '<STR_LIT>', None):<EOL><INDENT>return False<EOL><DEDENT>if self.name != getattr(other, '<STR_LIT:name>', None):<EOL><INDENT>return False<EOL><DEDENT>if self.version != getattr(other, '<STR_LIT:version>', None):<EOL><INDENT>return False<EOL><DEDENT>if self.is_substitute != getattr(other, '<STR_LIT>', None):<EOL><INDENT>return False<EOL><DEDENT>other_iter = getattr(other, '<STR_LIT>')<EOL>if not callable(other_iter):<EOL><INDENT>return False<EOL><DEDENT>for token, other_token in six.moves.zip_longest(self, other):<EOL><INDENT>if token != other_token:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
Compares two symbol tables together. Two symbol tables are considered equal if the underlying tokens are the same and the ``table_type``, ``name``, ``version``, and ``is_substitute`` attributes are defined and are equal. Note: This is implemented using ``getattr`` to allow duck-typed table implementations to compare. Any custom symbol table-like implementation should implement this method accordingly. Things that are not compared: * ``imports`` are never compared as they are denormalized into the tokens of the table. * ``max_id`` is never compared as its an invariant that it matches the iteration.
f5007:c3:m12
def register(self, table):
if table.table_type.is_system:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not table.table_type.is_shared:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if table.is_substitute:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>versions = self.__tables.get(table.name)<EOL>if versions is None:<EOL><INDENT>versions = {}<EOL>self.__tables[table.name] = versions<EOL><DEDENT>versions[table.version] = table<EOL>
Adds a shared table to the catalog. Args: table (SymbolTable): A non-system, shared symbol table.
f5007:c4:m1
def resolve(self, name, version, max_id):
if not isinstance(name, six.text_type):<EOL><INDENT>raise TypeError('<STR_LIT>' % name)<EOL><DEDENT>if not isinstance(version, int):<EOL><INDENT>raise TypeError('<STR_LIT>' % version)<EOL><DEDENT>if version <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % version)<EOL><DEDENT>if max_id is not None and max_id < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % max_id)<EOL><DEDENT>versions = self.__tables.get(name)<EOL>if versions is None:<EOL><INDENT>if max_id is None:<EOL><INDENT>raise CannotSubstituteTable(<EOL>'<STR_LIT>' % name<EOL>)<EOL><DEDENT>return placeholder_symbol_table(name, version, max_id)<EOL><DEDENT>table = versions.get(version)<EOL>if table is None:<EOL><INDENT>keys = list(versions)<EOL>keys.sort()<EOL>table = versions[keys[-<NUM_LIT:1>]]<EOL><DEDENT>if table.version == version and (max_id is None or table.max_id == max_id):<EOL><INDENT>return table<EOL><DEDENT>if max_id is None:<EOL><INDENT>raise CannotSubstituteTable(<EOL>'<STR_LIT>' % (name, version)<EOL>)<EOL><DEDENT>return substitute_symbol_table(table, version, max_id)<EOL>
Resolves the table for a given name and version. Args: name (unicode): The name of the table to resolve. version (int): The version of the table to resolve. max_id (Optional[int]): The maximum ID of the table requested. May be ``None`` in which case an exact match on ``name`` and ``version`` is required. Returns: SymbolTable: The *closest* matching symbol table. This is either an exact match, a placeholder, or a derived substitute depending on what tables are registered.
f5007:c4:m2
def _raw_binary_writer(writer_buffer):
return writer_trampoline(_raw_writer_coroutine(writer_buffer))<EOL>
Returns a raw binary writer co-routine. Yields: DataEvent: serialization events to write out Receives :class:`amazon.ion.core.IonEvent`.
f5008:m15
def start_container(self):
self.__container_lengths.append(self.current_container_length)<EOL>self.current_container_length = <NUM_LIT:0><EOL>new_container_node = _Node()<EOL>self.__container_node.add_child(new_container_node)<EOL>self.__container_nodes.append(self.__container_node)<EOL>self.__container_node = new_container_node<EOL>
Add a node to the tree that represents the start of a container. Until end_container is called, any nodes added through add_scalar_value or start_container will be children of this new node.
f5009:c1:m3
def end_container(self, header_buf):
if not self.__container_nodes:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.__container_node.add_leaf(_Node(header_buf))<EOL>self.__container_node = self.__container_nodes.pop()<EOL>parent_container_length = self.__container_lengths.pop()<EOL>self.current_container_length =parent_container_length + self.current_container_length + len(header_buf)<EOL>
Add a node containing the container's header to the current subtree. This node will be added as the leftmost leaf of the subtree that was started by the matching call to start_container. Args: header_buf (bytearray): bytearray containing the container header.
f5009:c1:m4
def add_scalar_value(self, value_buf):
self.__container_node.add_child(_Node(value_buf))<EOL>self.current_container_length += len(value_buf)<EOL>
Add a node to the tree containing a scalar value. Args: value_buf (bytearray): bytearray containing the scalar value.
f5009:c1:m5
def drain(self):
if self.__container_nodes:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for buf in self.__depth_traverse(self.__root):<EOL><INDENT>if buf is not None:<EOL><INDENT>yield buf<EOL><DEDENT><DEDENT>self.__reset()<EOL>
Walk the BufferTree and reset it when finished. Yields: any: The current node's value.
f5009:c1:m6
def _narrow_unichr(code_point):
try:<EOL><INDENT>if len(code_point.char) > <NUM_LIT:1>:<EOL><INDENT>return code_point.char<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>return six.unichr(code_point)<EOL>
Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds. This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2); ordinals above 0xFFFF would require recalculating and combining surrogate pairs. This avoids that by retrieving the unicode character that was initially read. Args: code_point (int|CodePoint): An int or a subclass of int that contains the unicode character representing its code point in an attribute named 'char'.
f5010:m0
def read_data_event(data):
return DataEvent(ReadEventType.DATA, data)<EOL>
Simple wrapper over the :class:`DataEvent` constructor to wrap a :class:`bytes` like with the ``DATA`` :class:`ReadEventType`. Args: data (bytes|unicode): The data for the event. Bytes are accepted by both binary and text readers, while unicode is accepted by text readers with is_unicode=True.
f5010:m1
@coroutine<EOL>def reader_trampoline(start, allow_flush=False):
data_event = yield<EOL>if data_event is None or data_event.type is not ReadEventType.NEXT:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>trans = Transition(None, start)<EOL>while True:<EOL><INDENT>trans = trans.delegate.send(Transition(data_event, trans.delegate))<EOL>data_event = None<EOL>if trans.event is not None:<EOL><INDENT>data_event = (yield trans.event)<EOL>if trans.event.event_type.is_stream_signal:<EOL><INDENT>if data_event.type is not ReadEventType.DATA:<EOL><INDENT>if not allow_flush or not (trans.event.event_type is IonEventType.INCOMPLETE and<EOL>data_event.type is ReadEventType.NEXT):<EOL><INDENT>raise TypeError('<STR_LIT>' % (data_event,))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if data_event.type is ReadEventType.DATA:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>if data_event.type is ReadEventType.DATA and len(data_event.data) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if trans.event.depth == <NUM_LIT:0>and trans.event.event_type is not IonEventType.CONTAINER_STARTand data_event.type is ReadEventType.SKIP:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>
Provides the co-routine trampoline for a reader state machine. The given co-routine is a state machine that yields :class:`Transition` and takes a Transition of :class:`amazon.ion.core.DataEvent` and the co-routine itself. A reader must start with a ``ReadEventType.NEXT`` event to prime the parser. In many cases this will lead to an ``IonEventType.INCOMPLETE`` being yielded, but not always (consider a reader over an in-memory data structure). Notes: A reader delimits its incomplete parse points with ``IonEventType.INCOMPLETE``. Readers also delimit complete parse points with ``IonEventType.STREAM_END``; this is similar to the ``INCOMPLETE`` case except that it denotes that a logical termination of data is *allowed*. When these event are received, the only valid input event type is a ``ReadEventType.DATA``. Generally, ``ReadEventType.NEXT`` is used to get the next parse event, but ``ReadEventType.SKIP`` can be used to skip over the current container. An internal state machine co-routine can delimit a state change without yielding to the caller by yielding ``None`` event, this will cause the trampoline to invoke the transition delegate, immediately. Args: start: The reader co-routine to initially delegate to. allow_flush(Optional[bool]): True if this reader supports receiving ``NEXT`` after yielding ``INCOMPLETE`` to trigger an attempt to flush pending parse events, otherwise False. Yields: amazon.ion.core.IonEvent: the result of parsing. Receives :class:`DataEvent` to parse into :class:`amazon.ion.core.IonEvent`.
f5010:m2
@coroutine<EOL>def blocking_reader(reader, input, buffer_size=_DEFAULT_BUFFER_SIZE):
ion_event = None<EOL>while True:<EOL><INDENT>read_event = (yield ion_event)<EOL>ion_event = reader.send(read_event)<EOL>while ion_event is not None and ion_event.event_type.is_stream_signal:<EOL><INDENT>data = input.read(buffer_size)<EOL>if len(data) == <NUM_LIT:0>:<EOL><INDENT>if ion_event.event_type is IonEventType.INCOMPLETE:<EOL><INDENT>ion_event = reader.send(NEXT_EVENT)<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>yield ION_STREAM_END_EVENT<EOL>return<EOL><DEDENT><DEDENT>ion_event = reader.send(read_data_event(data))<EOL><DEDENT><DEDENT>
Provides an implementation of using the reader co-routine with a file-like object. Args: reader(Coroutine): A reader co-routine. input(BaseIO): The file-like object to read from. buffer_size(Optional[int]): The optional buffer size to use.
f5010:m3
def read(self, length, skip=False):
if length > self.__size:<EOL><INDENT>raise IndexError(<EOL>'<STR_LIT>' % (length, self.__size))<EOL><DEDENT>self.position += length<EOL>self.__size -= length<EOL>segments = self.__segments<EOL>offset = self.__offset<EOL>data = self.__data_cls()<EOL>while length > <NUM_LIT:0>:<EOL><INDENT>segment = segments[<NUM_LIT:0>]<EOL>segment_off = offset<EOL>segment_len = len(segment)<EOL>segment_rem = segment_len - segment_off<EOL>segment_read_len = min(segment_rem, length)<EOL>if segment_off == <NUM_LIT:0> and segment_read_len == segment_rem:<EOL><INDENT>if skip:<EOL><INDENT>segment_slice = self.__element_type()<EOL><DEDENT>else:<EOL><INDENT>segment_slice = segment<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if skip:<EOL><INDENT>segment_slice = self.__element_type()<EOL><DEDENT>else:<EOL><INDENT>segment_slice = segment[segment_off:segment_off + segment_read_len]<EOL><DEDENT>offset = <NUM_LIT:0><EOL><DEDENT>segment_off += segment_read_len<EOL>if segment_off == segment_len:<EOL><INDENT>segments.popleft()<EOL>self.__offset = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>self.__offset = segment_off<EOL><DEDENT>if length <= segment_rem and len(data) == <NUM_LIT:0>:<EOL><INDENT>return segment_slice<EOL><DEDENT>data.extend(segment_slice)<EOL>length -= segment_read_len<EOL><DEDENT>if self.is_unicode:<EOL><INDENT>return data.as_text()<EOL><DEDENT>else:<EOL><INDENT>return data<EOL><DEDENT>
Consumes the first ``length`` bytes from the accumulator.
f5010:c2:m5
def unread(self, c):
if self.position < <NUM_LIT:1>:<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT>if isinstance(c, six.text_type):<EOL><INDENT>if not self.is_unicode:<EOL><INDENT>BufferQueue._incompatible_types(self.is_unicode, c)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>c = self.__chr(c)<EOL><DEDENT>num_code_units = self.is_unicode and len(c) or <NUM_LIT:1><EOL>if self.__offset == <NUM_LIT:0>:<EOL><INDENT>if num_code_units == <NUM_LIT:1> and six.PY3:<EOL><INDENT>if self.is_unicode:<EOL><INDENT>segment = c<EOL><DEDENT>else:<EOL><INDENT>segment = six.int2byte(c)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>segment = c<EOL><DEDENT>self.__segments.appendleft(segment)<EOL><DEDENT>else:<EOL><INDENT>self.__offset -= num_code_units<EOL>def verify(ch, idx):<EOL><INDENT>existing = self.__segments[<NUM_LIT:0>][self.__offset + idx]<EOL>if existing != ch:<EOL><INDENT>raise ValueError('<STR_LIT>' % (ch, existing))<EOL><DEDENT><DEDENT>if num_code_units == <NUM_LIT:1>:<EOL><INDENT>verify(c, <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>for i in range(num_code_units):<EOL><INDENT>verify(c[i], i)<EOL><DEDENT><DEDENT><DEDENT>self.__size += num_code_units<EOL>self.position -= num_code_units<EOL>
Unread the given character, byte, or code point. If this is a unicode buffer and the input is an int or byte, it will be interpreted as an ordinal representing a unicode code point. If this is a binary buffer, the input must be a byte or int; a unicode character will raise an error.
f5010:c2:m7
def skip(self, length):
if length >= self.__size:<EOL><INDENT>skip_amount = self.__size<EOL>rem = length - skip_amount<EOL>self.__segments.clear()<EOL>self.__offset = <NUM_LIT:0><EOL>self.__size = <NUM_LIT:0><EOL>self.position += skip_amount<EOL><DEDENT>else:<EOL><INDENT>rem = <NUM_LIT:0><EOL>self.read(length, skip=True)<EOL><DEDENT>return rem<EOL>
Removes ``length`` bytes and returns the number length still required to skip
f5010:c2:m8
def _gen_type_octet(hn, ln):
return (hn << <NUM_LIT:4>) | ln<EOL>
Generates a type octet from a high nibble and low nibble.
f5012:m0
def _parse_var_int_components(buf, signed):
value = <NUM_LIT:0><EOL>sign = <NUM_LIT:1><EOL>while True:<EOL><INDENT>ch = buf.read(<NUM_LIT:1>)<EOL>if ch == '<STR_LIT>':<EOL><INDENT>raise IonException('<STR_LIT>')<EOL><DEDENT>octet = ord(ch)<EOL>if signed:<EOL><INDENT>if octet & _VAR_INT_SIGN_MASK:<EOL><INDENT>sign = -<NUM_LIT:1><EOL><DEDENT>value = octet & _VAR_INT_SIGN_VALUE_MASK<EOL>signed = False<EOL><DEDENT>else:<EOL><INDENT>value <<= _VAR_INT_VALUE_BITS<EOL>value |= octet & _VAR_INT_VALUE_MASK<EOL><DEDENT>if octet & _VAR_INT_SIGNAL_MASK:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return sign, value<EOL>
Parses a ``VarInt`` or ``VarUInt`` field from a file-like object.
f5012:m1
def _parse_signed_int_components(buf):
sign_bit = <NUM_LIT:0><EOL>value = <NUM_LIT:0><EOL>first = True<EOL>while True:<EOL><INDENT>ch = buf.read(<NUM_LIT:1>)<EOL>if ch == b'<STR_LIT>':<EOL><INDENT>break<EOL><DEDENT>octet = ord(ch)<EOL>if first:<EOL><INDENT>if octet & _SIGNED_INT_SIGN_MASK:<EOL><INDENT>sign_bit = <NUM_LIT:1><EOL><DEDENT>value = octet & _SIGNED_INT_SIGN_VALUE_MASK<EOL>first = False<EOL><DEDENT>else:<EOL><INDENT>value <<= <NUM_LIT:8><EOL>value |= octet<EOL><DEDENT><DEDENT>return sign_bit, value<EOL>
Parses the remainder of a file-like object as a signed magnitude value. Returns: Returns a pair of the sign bit and the unsigned magnitude.
f5012:m3
def _parse_decimal(buf):
exponent = _parse_var_int(buf, signed=True)<EOL>sign_bit, coefficient = _parse_signed_int_components(buf)<EOL>if coefficient == <NUM_LIT:0>:<EOL><INDENT>value = Decimal((sign_bit, (<NUM_LIT:0>,), exponent))<EOL><DEDENT>else:<EOL><INDENT>coefficient *= sign_bit and -<NUM_LIT:1> or <NUM_LIT:1><EOL>value = Decimal(coefficient).scaleb(exponent)<EOL><DEDENT>return value<EOL>
Parses the remainder of a file-like object as a decimal.
f5012:m4
def _parse_sid_iter(data):
limit = len(data)<EOL>buf = BytesIO(data)<EOL>while buf.tell() < limit:<EOL><INDENT>sid = _parse_var_int(buf, signed=False)<EOL>yield SymbolToken(None, sid)<EOL><DEDENT>
Parses the given :class:`bytes` data as a list of :class:`SymbolToken`
f5012:m5
def _create_delegate_handler(delegate):
@coroutine<EOL>def handler(*args):<EOL><INDENT>yield<EOL>yield delegate.send(Transition(args, delegate))<EOL><DEDENT>return handler<EOL>
Creates a handler function that creates a co-routine that can yield once with the given positional arguments to the delegate as a transition. Args: delegate (Coroutine): The co-routine to delegate to. Returns: A :class:`callable` handler that returns a co-routine that ignores the data it receives and sends with the arguments given to the handler as a :class:`Transition`.
f5012:m6
@coroutine<EOL>def _read_data_handler(length, whence, ctx, skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT):
trans = None<EOL>queue = ctx.queue<EOL>if length > ctx.remaining:<EOL><INDENT>raise IonException('<STR_LIT>' % (length, ctx.remaining))<EOL><DEDENT>queue_len = len(queue)<EOL>if queue_len > <NUM_LIT:0>:<EOL><INDENT>stream_event = ION_STREAM_INCOMPLETE_EVENT<EOL><DEDENT>length -= queue_len<EOL>if skip:<EOL><INDENT>if length >= <NUM_LIT:0>:<EOL><INDENT>queue.skip(queue_len)<EOL><DEDENT>else:<EOL><INDENT>queue.skip(queue_len + length)<EOL><DEDENT><DEDENT>while True:<EOL><INDENT>data_event, self = (yield trans)<EOL>if data_event is not None and 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>stream_event = ION_STREAM_INCOMPLETE_EVENT<EOL><DEDENT>length -= data_len<EOL>if not skip:<EOL><INDENT>queue.extend(data)<EOL><DEDENT>else:<EOL><INDENT>pos_adjustment = data_len<EOL>if length < <NUM_LIT:0>:<EOL><INDENT>pos_adjustment += length<EOL>queue.extend(data[length:])<EOL><DEDENT>queue.position += pos_adjustment<EOL><DEDENT><DEDENT>if length <= <NUM_LIT:0>:<EOL><INDENT>yield Transition(None, whence)<EOL><DEDENT>trans = Transition(stream_event, self)<EOL><DEDENT>
Creates a co-routine for retrieving data up to a requested size. Args: length (int): The minimum length requested. whence (Coroutine): The co-routine to return to after the data is satisfied. ctx (_HandlerContext): The context for the read. skip (Optional[bool]): Whether the requested number of bytes should be skipped. stream_event (Optional[IonEvent]): The stream event to return if no bytes are read or available.
f5012:m7
@coroutine<EOL>def _invalid_handler(type_octet, ctx):
yield<EOL>raise IonException('<STR_LIT>' % type_octet)<EOL>
Placeholder co-routine for invalid type codes.
f5012:m8
@coroutine<EOL>def _var_uint_field_handler(handler, ctx):
_, self = yield<EOL>queue = ctx.queue<EOL>value = <NUM_LIT:0><EOL>while True:<EOL><INDENT>if len(queue) == <NUM_LIT:0>:<EOL><INDENT>yield ctx.read_data_transition(<NUM_LIT:1>, self)<EOL><DEDENT>octet = queue.read_byte()<EOL>value <<= _VAR_INT_VALUE_BITS<EOL>value |= octet & _VAR_INT_VALUE_MASK<EOL>if octet & _VAR_INT_SIGNAL_MASK:<EOL><INDENT>break<EOL><DEDENT><DEDENT>yield ctx.immediate_transition(handler(value, ctx))<EOL>
Handler co-routine for variable unsigned integer fields that. Invokes the given ``handler`` function with the read field and context, then immediately yields to the resulting co-routine.
f5012:m9
@coroutine<EOL>def _length_scalar_handler(scalar_factory, ion_type, length, ctx):
_, self = yield<EOL>if length == <NUM_LIT:0>:<EOL><INDENT>data = b'<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>yield ctx.read_data_transition(length, self)<EOL>data = ctx.queue.read(length)<EOL><DEDENT>scalar = scalar_factory(data)<EOL>event_cls = IonEvent<EOL>if callable(scalar):<EOL><INDENT>event_cls = IonThunkEvent<EOL><DEDENT>yield ctx.event_transition(event_cls, IonEventType.SCALAR, ion_type, scalar)<EOL>
Handles scalars, ``scalar_factory`` is a function that returns a value or thunk.
f5012:m13
@coroutine<EOL>def _annotation_handler(ion_type, length, ctx):
_, self = yield<EOL>self_handler = _create_delegate_handler(self)<EOL>if ctx.annotations is not None:<EOL><INDENT>raise IonException('<STR_LIT>')<EOL><DEDENT>ctx = ctx.derive_container_context(length, add_depth=<NUM_LIT:0>)<EOL>(ann_length, _), _ = yield ctx.immediate_transition(<EOL>_var_uint_field_handler(self_handler, ctx)<EOL>)<EOL>if ann_length < <NUM_LIT:1>:<EOL><INDENT>raise IonException('<STR_LIT>')<EOL><DEDENT>yield ctx.read_data_transition(ann_length, self)<EOL>ann_data = ctx.queue.read(ann_length)<EOL>annotations = tuple(_parse_sid_iter(ann_data))<EOL>if ctx.limit - ctx.queue.position < <NUM_LIT:1>:<EOL><INDENT>raise IonException('<STR_LIT>')<EOL><DEDENT>yield ctx.immediate_transition(<EOL>_start_type_handler(ctx.field_name, ctx.whence, ctx, annotations=annotations)<EOL>)<EOL>
Handles annotations. ``ion_type`` is ignored.
f5012:m15
@coroutine<EOL>def _ordered_struct_start_handler(handler, ctx):
_, self = yield<EOL>self_handler = _create_delegate_handler(self)<EOL>(length, _), _ = yield ctx.immediate_transition(<EOL>_var_uint_field_handler(self_handler, ctx)<EOL>)<EOL>if length < <NUM_LIT:2>:<EOL><INDENT>raise IonException('<STR_LIT>')<EOL><DEDENT>yield ctx.immediate_transition(handler(length, ctx))<EOL>
Handles the special case of ordered structs, specified by the type ID 0xD1. This coroutine's only purpose is to ensure that the struct in question declares at least one field name/value pair, as required by the spec.
f5012:m16
@coroutine<EOL>def _container_start_handler(ion_type, length, ctx):
_, self = yield<EOL>container_ctx = ctx.derive_container_context(length)<EOL>if ctx.annotations and ctx.limit != container_ctx.limit:<EOL><INDENT>raise IonException('<STR_LIT>')<EOL><DEDENT>delegate = _container_handler(ion_type, container_ctx)<EOL>yield ctx.event_transition(<EOL>IonEvent, IonEventType.CONTAINER_START, ion_type, value=None, whence=delegate<EOL>)<EOL>
Handles container delegation.
f5012:m17
@coroutine<EOL>def _container_handler(ion_type, ctx):
transition = None<EOL>first = True<EOL>at_top = ctx.depth == <NUM_LIT:0><EOL>while True:<EOL><INDENT>data_event, self = (yield transition)<EOL>if data_event is not None and data_event.type is ReadEventType.SKIP:<EOL><INDENT>yield ctx.read_data_transition(ctx.remaining, self, skip=True)<EOL><DEDENT>if ctx.queue.position == ctx.limit:<EOL><INDENT>yield Transition(<EOL>IonEvent(IonEventType.CONTAINER_END, ion_type, depth=ctx.depth-<NUM_LIT:1>),<EOL>ctx.whence<EOL>)<EOL><DEDENT>if ion_type is IonType.STRUCT:<EOL><INDENT>self_handler = _create_delegate_handler(self)<EOL>(field_sid, _), _ = yield ctx.immediate_transition(<EOL>_var_uint_field_handler(self_handler, ctx)<EOL>)<EOL>field_name = SymbolToken(None, field_sid)<EOL><DEDENT>else:<EOL><INDENT>field_name = None<EOL><DEDENT>expects_ivm = first and at_top<EOL>transition = ctx.immediate_transition(<EOL>_start_type_handler(field_name, self, ctx, expects_ivm, at_top=at_top)<EOL>)<EOL>first = False<EOL><DEDENT>
Handler for the body of a container (or the top-level stream). Args: ion_type (Optional[IonType]): The type of the container or ``None`` for the top-level. ctx (_HandlerContext): The context for the container.
f5012:m18
def _bind_invalid_handlers():
for type_octet in range(<NUM_LIT>):<EOL><INDENT>_HANDLER_DISPATCH_TABLE[type_octet] = partial(_invalid_handler, type_octet)<EOL><DEDENT>
Seeds the co-routine table with all invalid handlers.
f5012:m27
def _bind_length_handlers(tids, user_handler, lns):
for tid in tids:<EOL><INDENT>for ln in lns:<EOL><INDENT>type_octet = _gen_type_octet(tid, ln)<EOL>ion_type = _TID_VALUE_TYPE_TABLE[tid]<EOL>if ln == <NUM_LIT:1> and ion_type is IonType.STRUCT:<EOL><INDENT>handler = partial(_ordered_struct_start_handler, partial(user_handler, ion_type))<EOL><DEDENT>elif ln < _LENGTH_FIELD_FOLLOWS:<EOL><INDENT>handler = partial(user_handler, ion_type, ln)<EOL><DEDENT>else:<EOL><INDENT>handler = partial(_var_uint_field_handler, partial(user_handler, ion_type))<EOL><DEDENT>_HANDLER_DISPATCH_TABLE[type_octet] = handler<EOL><DEDENT><DEDENT>
Binds a set of handlers with the given factory. Args: tids (Sequence[int]): The Type IDs to bind to. user_handler (Callable): A function that takes as its parameters :class:`IonType`, ``length``, and the ``ctx`` context returning a co-routine. lns (Sequence[int]): The low-nibble lengths to bind to.
f5012:m30
def _bind_length_scalar_handlers(tids, scalar_factory, lns=_NON_ZERO_LENGTH_LNS):
handler = partial(_length_scalar_handler, scalar_factory)<EOL>return _bind_length_handlers(tids, handler, lns)<EOL>
Binds a set of scalar handlers for an inclusive range of low-nibble values. Args: tids (Sequence[int]): The Type IDs to bind to. scalar_factory (Callable): The factory for the scalar parsing function. This function can itself return a function representing a thunk to defer the scalar parsing or a direct value. lns (Sequence[int]): The low-nibble lengths to bind to.
f5012:m31
def raw_reader(queue=None):
if queue is None:<EOL><INDENT>queue = BufferQueue()<EOL><DEDENT>ctx = _HandlerContext(<EOL>position=<NUM_LIT:0>,<EOL>limit=None,<EOL>queue=queue,<EOL>field_name=None,<EOL>annotations=None,<EOL>depth=<NUM_LIT:0>,<EOL>whence=None<EOL>)<EOL>return reader_trampoline(_container_handler(None, ctx))<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. 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, or ``DATA`` if the last event was a ``INCOMPLETE`` or ``STREAM_END`` event type. ``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.
f5012:m32
@property<EOL><INDENT>def remaining(self):<DEDENT>
if self.depth == <NUM_LIT:0>:<EOL><INDENT>return _STREAM_REMAINING<EOL><DEDENT>return self.limit - self.queue.position<EOL>
Determines how many bytes are remaining in the current context.
f5012:c1:m0
def read_data_transition(self, length, whence=None,<EOL>skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT):
if whence is None:<EOL><INDENT>whence = self.whence<EOL><DEDENT>return Transition(<EOL>None, _read_data_handler(length, whence, self, skip, stream_event)<EOL>)<EOL>
Returns an immediate event_transition to read a specified number of bytes.
f5012:c1:m1
def event_transition(self, event_cls, event_type,<EOL>ion_type=None, value=None, annotations=None, depth=None, whence=None):
if annotations is None:<EOL><INDENT>annotations = self.annotations<EOL><DEDENT>if annotations is None:<EOL><INDENT>annotations = ()<EOL><DEDENT>if not (event_type is IonEventType.CONTAINER_START) andannotations and (self.limit - self.queue.position) != <NUM_LIT:0>:<EOL><INDENT>raise IonException('<STR_LIT>')<EOL><DEDENT>if depth is None:<EOL><INDENT>depth = self.depth<EOL><DEDENT>if whence is None:<EOL><INDENT>whence = self.whence<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. If ``annotations`` is not specified, then the ``annotations`` are the annotations of this context. If ``depth`` is not specified, then the ``depth`` is depth of this context. If ``whence`` is not specified, then ``whence`` is the whence of this context.
f5012:c1:m2
def immediate_transition(self, delegate=None):
if delegate is None:<EOL><INDENT>delegate = self.whence<EOL><DEDENT>return Transition(None, delegate)<EOL>
Returns an immediate transition to another co-routine. If ``delegate`` is not specified, then ``whence`` is the delegate.
f5012:c1:m3
def timestamp(year, month=<NUM_LIT:1>, day=<NUM_LIT:1>,<EOL>hour=<NUM_LIT:0>, minute=<NUM_LIT:0>, second=<NUM_LIT:0>, microsecond=None,<EOL>off_hours=None, off_minutes=None,<EOL>precision=None, fractional_precision=None):
delta = None<EOL>if off_hours is not None:<EOL><INDENT>if off_hours < -<NUM_LIT> or off_hours > <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>' % (off_hours,))<EOL><DEDENT>delta = timedelta(hours=off_hours)<EOL><DEDENT>if off_minutes is not None:<EOL><INDENT>if off_minutes < -<NUM_LIT> or off_minutes > <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>' % (off_minutes,))<EOL><DEDENT>minutes_delta = timedelta(minutes=off_minutes)<EOL>if delta is None:<EOL><INDENT>delta = minutes_delta<EOL><DEDENT>else:<EOL><INDENT>delta += minutes_delta<EOL><DEDENT><DEDENT>tz = None<EOL>if delta is not None:<EOL><INDENT>tz = OffsetTZInfo(delta)<EOL><DEDENT>if microsecond is not None:<EOL><INDENT>if fractional_precision is None:<EOL><INDENT>fractional_precision = MICROSECOND_PRECISION<EOL><DEDENT><DEDENT>else:<EOL><INDENT>microsecond = <NUM_LIT:0><EOL>if fractional_precision is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>return Timestamp(<EOL>year, month, day,<EOL>hour, minute, second, microsecond,<EOL>tz, precision=precision, fractional_precision=fractional_precision<EOL>)<EOL>
Shorthand for the :class:`Timestamp` constructor. Specifically, converts ``off_hours`` and ``off_minutes`` parameters to a suitable :class:`OffsetTZInfo` instance.
f5013:m0
@property<EOL><INDENT>def is_text(self):<DEDENT>
return self is IonType.SYMBOL or self is IonType.STRING<EOL>
Returns whether the type is a Unicode textual type.
f5013:c0:m1
@property<EOL><INDENT>def is_lob(self):<DEDENT>
return self is IonType.CLOB or self is IonType.BLOB<EOL>
Returns whether the type is a LOB.
f5013:c0:m2
@property<EOL><INDENT>def is_container(self):<DEDENT>
return self >= IonType.LIST<EOL>
Returns whether the type is a container.
f5013:c0:m3
@property<EOL><INDENT>def begins_value(self):<DEDENT>
return self is IonEventType.SCALAR or self is IonEventType.CONTAINER_START<EOL>
Indicates if the event type is a start of a value.
f5013:c1:m0
@property<EOL><INDENT>def ends_container(self):<DEDENT>
return self is IonEventType.STREAM_END or self is IonEventType.CONTAINER_END<EOL>
Indicates if the event type terminates a container or stream.
f5013:c1:m1
@property<EOL><INDENT>def is_stream_signal(self):<DEDENT>
return self < <NUM_LIT:0><EOL>
Indicates that the event type corresponds to a stream signal.
f5013:c1:m2
def derive_field_name(self, field_name):
cls = type(self)<EOL>return cls(<EOL>self[<NUM_LIT:0>],<EOL>self[<NUM_LIT:1>],<EOL>self[<NUM_LIT:2>],<EOL>field_name,<EOL>self[<NUM_LIT:4>],<EOL>self[<NUM_LIT:5>]<EOL>)<EOL>
Derives a new event from this one setting the ``field_name`` attribute. Args: field_name (Union[amazon.ion.symbols.SymbolToken, unicode]): The field name to set. Returns: IonEvent: The newly generated event.
f5013:c2:m1
def derive_annotations(self, annotations):
cls = type(self)<EOL>return cls(<EOL>self[<NUM_LIT:0>],<EOL>self[<NUM_LIT:1>],<EOL>self[<NUM_LIT:2>],<EOL>self[<NUM_LIT:3>],<EOL>annotations,<EOL>self[<NUM_LIT:5>]<EOL>)<EOL>
Derives a new event from this one setting the ``annotations`` attribute. Args: annotations: (Sequence[Union[amazon.ion.symbols.SymbolToken, unicode]]): The annotations associated with the derived event. Returns: IonEvent: The newly generated event.
f5013:c2:m2
def derive_value(self, value):
return IonEvent(<EOL>self.event_type,<EOL>self.ion_type,<EOL>value,<EOL>self.field_name,<EOL>self.annotations,<EOL>self.depth<EOL>)<EOL>
Derives a new event from this one setting the ``value`` attribute. Args: value: (any): The value associated with the derived event. Returns: IonEvent: The newly generated non-thunk event.
f5013:c2:m3
def derive_depth(self, depth):
cls = type(self)<EOL>return cls(<EOL>self[<NUM_LIT:0>],<EOL>self[<NUM_LIT:1>],<EOL>self[<NUM_LIT:2>],<EOL>self[<NUM_LIT:3>],<EOL>self[<NUM_LIT:4>],<EOL>depth<EOL>)<EOL>
Derives a new event from this one setting the ``depth`` attribute. Args: depth: (int): The annotations associated with the derived event. Returns: IonEvent: The newly generated event.
f5013:c2:m4
@property<EOL><INDENT>def includes_month(self):<DEDENT>
return self >= TimestampPrecision.MONTH<EOL>
Precision has at least the ``month`` field.
f5013:c8:m0
@property<EOL><INDENT>def includes_day(self):<DEDENT>
return self >= TimestampPrecision.DAY<EOL>
Precision has at least the ``day`` field.
f5013:c8:m1
@property<EOL><INDENT>def includes_minute(self):<DEDENT>
return self >= TimestampPrecision.MINUTE<EOL>
Precision has at least the ``minute`` field.
f5013:c8:m2
@property<EOL><INDENT>def includes_second(self):<DEDENT>
return self >= TimestampPrecision.SECOND<EOL>
Precision has at least the ``second`` field.
f5013:c8:m3
@staticmethod<EOL><INDENT>def adjust_from_utc_fields(*args, **kwargs):<DEDENT>
raw_ts = Timestamp(*args, **kwargs)<EOL>offset = raw_ts.utcoffset()<EOL>if offset is None or offset == timedelta():<EOL><INDENT>return raw_ts<EOL><DEDENT>adjusted = raw_ts + offset<EOL>if raw_ts.precision is None:<EOL><INDENT>return adjusted<EOL><DEDENT>return Timestamp(<EOL>adjusted.year,<EOL>adjusted.month,<EOL>adjusted.day,<EOL>adjusted.hour,<EOL>adjusted.minute,<EOL>adjusted.second,<EOL>adjusted.microsecond,<EOL>raw_ts.tzinfo,<EOL>precision=raw_ts.precision,<EOL>fractional_precision=raw_ts.fractional_precision<EOL>)<EOL>
Constructs a timestamp from UTC fields adjusted to the local offset if given.
f5013:c9:m2
def _write_varint(buf, value):
return _write_signed(buf, value, _field_cache.get_varint, _write_varint_uncached)<EOL>
Writes the given integer value into the given buffer as a binary Ion VarInt field. Args: buf (Sequence): The buffer into which the VarInt will be written, in the form of integer octets. value (int): The value to write as a VarInt. Returns: int: The number of octets written.
f5014:m0
def _write_int(buf, value):
return _write_signed(buf, value, _field_cache.get_int, _write_int_uncached)<EOL>
Writes the given integer value into the given buffer as a binary Ion Int field. Args: buf (Sequence): The buffer into which the Int will be written, in the form of integer octets. value (int): The value to write as a Int. Returns: int: The number of octets written.
f5014:m2
def _write_varuint(buf, value):
return _write_unsigned(buf, value, _field_cache.get_varuint, _write_varuint_uncached)<EOL>
Writes the given integer value into the given buffer as a binary Ion VarUInt. Args: buf (Sequence): The buffer into which the VarUInt will be written, in the form of integer octets. value (int): The value to write as a VarUInt. Returns: int: The number of octets written.
f5014:m6
def _write_uint(buf, value):
return _write_unsigned(buf, value, _field_cache.get_uint, _write_uint_uncached)<EOL>
Writes the given integer value into the given buffer as a binary Ion UInt. Args: buf (Sequence): The buffer into which the UInt will be written, in the form of integer octets. value (int): The value to write as a UInt. Returns: int: The number of octets written.
f5014:m8
def _write_base(buf, value, bits_per_octet, end_bit=<NUM_LIT:0>, sign_bit=<NUM_LIT:0>, is_signed=False):
if value == <NUM_LIT:0>:<EOL><INDENT>buf.append(sign_bit | end_bit)<EOL>return <NUM_LIT:1><EOL><DEDENT>num_bits = bit_length(value)<EOL>num_octets = num_bits // bits_per_octet<EOL>remainder = num_bits % bits_per_octet<EOL>if remainder != <NUM_LIT:0> or is_signed:<EOL><INDENT>num_octets += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>remainder = bits_per_octet<EOL><DEDENT>for i in range(num_octets):<EOL><INDENT>octet = <NUM_LIT:0><EOL>if i == <NUM_LIT:0>:<EOL><INDENT>octet |= sign_bit<EOL><DEDENT>if i == num_octets - <NUM_LIT:1>:<EOL><INDENT>octet |= end_bit<EOL><DEDENT>octet |= ((value >> (num_bits - (remainder + bits_per_octet * i))) & _OCTET_MASKS[bits_per_octet])<EOL>buf.append(octet)<EOL><DEDENT>return num_octets<EOL>
Write a field to the provided buffer. Args: buf (Sequence): The buffer into which the UInt will be written in the form of integer octets. value (int): The value to write as a UInt. bits_per_octet (int): The number of value bits (i.e. exclusive of the end bit, but inclusive of the sign bit, if applicable) per octet. end_bit (Optional[int]): The end bit mask. sign_bit (Optional[int]): The sign bit mask. Returns: int: The number of octets written.
f5014:m11
def _raw_symbol_writer(writer_buffer, imports):
return writer_trampoline(_symbol_table_coroutine(writer_buffer, imports))<EOL>
Returns a raw binary symbol table writer co-routine. Keyword Args: writer_buffer (BufferTree): The buffer in which this writer's values will be stored. 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:m3