PKNˣpreconvert/__init__.py"""A Library to enable preconversion of any Python type into one that is easily serializable""" __version__ = "0.0.2" from preconvert import convert, exceptions, output from preconvert.convert import unserializable from preconvert.register import bson, converter, json, msgpack __all__ = [ "converter", "json", "bson", "msgpack", "exceptions", "convert", "output", "unserializable", ] PK vNQpreconvert/convert.pyfrom collections import ChainMap from functools import partial from typing import Any, Callable, Dict, Text from preconvert.exceptions import Unconvertable from preconvert.register import converters def unserializable( item: Any, namespace: Text = "base", base_namespace: Text = "base", store: Dict[Text, Dict[Any, Callable]] = converters, ): if hasattr(item, "__native_types__"): return item.__native_types__() if base_namespace and namespace != base_namespace: preconverters = ChainMap(store.get(namespace, {}), store["base"]).items() else: preconverters = store[base_namespace].items() for kind, transformer in reversed(tuple(preconverters)): if isinstance(item, kind): return transformer(item) if hasattr(item, "__iter__"): return list(item) raise Unconvertable(item) json = partial(unserializable, namespace="json") bson = partial(unserializable, namespace="bson") msgpack = partial(unserializable, namespace="msgpack") PK!N#{ preconvert/converters.pyimport base64 from datetime import date, datetime, timedelta from decimal import Decimal from enum import Enum from types import GeneratorType from typing import Any, Collection, Dict, Mapping, NamedTuple, Union from uuid import UUID from preconvert import register from preconvert.exceptions import Unconvertable try: import dataclasses dataclasses_loaded = True except ImportError: dataclasses_loaded = False try: import numpy numpy_loaded = True except ImportError: numpy_loaded = False if dataclasses_loaded: @register.converter(object) def convert_data_class(instance): if dataclasses.is_dataclass(instance): return dataclasses.asdict(instance) else: raise Unconvertable(instance) register.converter(Collection)(list) register.converter(GeneratorType)(tuple) register.converter(Mapping)(dict) register.converter(Decimal, UUID)(str) @register.converter(bytes) def byte_converter(item): try: return item.decode("utf8") except UnicodeDecodeError: return base64.b64encode(item) @register.converter(date, datetime) def datetime_converter(item): return item.isoformat() @register.converter(timedelta) def time_delta_converter(item): return item.total_seconds() @register.converter(Enum) def use_value_attribute(item): return item.value @register.convert(NamedTuple) def convert_namedtuple(instance: Any) -> Union[Dict, tuple]: """Converts a tuple of type namedtuple to a dict. This isn't registered as injecting this via registration won't work because it will never be falling through to as tuples convert to list. if the tuple isn't a named one, it will return the tuple unchanged """ if hasattr(instance, "_asdict"): return instance._asdict() return instance if numpy_loaded: @register.converter(numpy.ndarray) def numpy_listable(item): return item.tolist() @register.converter(str, numpy.unicode_) def numpy_stringable(item): return str(item) @register.converter(numpy.bytes_) def numpy_byte_decodeable(item): return item.decode() @register.converter(numpy.bool_) def numpy_boolable(item): return bool(item) @register.converter(numpy.integer) def numpy_integerable(item): return int(item) @register.converter(float, numpy.floating) def numpy_floatable(item): return float(item) PK Callable: """A decorator that registers the wrapped function as a pre-converter for the provided types in the provided `store` data structure or a default global one. Returns the decorated function unchanged. """ def register_converter(function): if not override: for kind in kinds: if kind in store[scope]: raise ExistingConverter(kind, store[scope], function) for kind in kinds: # we redo this loop simply to guard against partial application store[scope][kind] = function return function return register_converter json = partial(converter, scope="json") bson = partial(converter, scope="bson") msgpack = partial(converter, scope="msgpack") PKcNPPpreconvert/output/__init__.py"""Exposes all output formatters that have built-in support for preconversion Note: the interesting try: catch: pattern is done as their isn't a guarantee that the user has any of the given output formatters installed, which is required for preconvert to plug-in it's preconversion. """ try: from preconvert.output import json except ImportError: pass try: from preconvert.output import bson except ImportError: pass try: from preconvert.output import msgpack except ImportError: pass try: from preconvert.output import simplejson except ImportError: pass PK4NXbpreconvert/output/bson.pyimport bson from bson import * from preconvert import convert from preconvert.converters import convert_namedtuple def dumps(content, *args, on_unknown=convert.bson, **kwargs): # type: ignore """BSON dumps with preconversion for common unserializable types in place""" if isinstance(content, tuple): content = convert_namedtuple(content) return bson.dumps(content, on_unknown=on_unknown, *args, **kwargs) def dump(content, *args, on_unknown=convert.bson, **kwargs): # type: ignore """BSON dump with preconversion for common unserializable types in place""" if isinstance(content, tuple): content = convert_namedtuple(content) return bson.dump(content, on_unknown=on_unknown, *args, **kwargs) PK\N9preconvert/output/json.pyimport json from json import * from preconvert import convert from preconvert.converters import convert_namedtuple def dumps(content, *args, default=convert.json, **kwargs): # type: ignore """JSON dumps with preconversion for common unserializable types in place""" if isinstance(content, tuple): content = convert_namedtuple(content) return json.dumps(content, default=default, *args, **kwargs) def dump(content, *args, default=convert.json, **kwargs): # type: ignore """JSON dump with preconversion for common unserializable types in place""" if isinstance(content, tuple): content = convert_namedtuple(content) return json.dump(content, default=default, *args, **kwargs) PKNnѲOOpreconvert/output/msgpack.pyimport msgpack from msgpack import * from preconvert import convert from preconvert.converters import convert_namedtuple def pack(content, *args, default=convert.msgpack, **kwargs): # type: ignore """Msgpacks with preconversion for common unserializable types in place""" if isinstance(content, tuple): content = convert_namedtuple(content) return msgpack.pack(content, default=default, *args, **kwargs) def packb(content, *args, default=convert.msgpack, **kwargs): # type: ignore """Msgpacks with preconversion for common unserializable types in place""" if isinstance(content, tuple): content = convert_namedtuple(content) return msgpack.packb(content, default=default, *args, **kwargs) def dump(content, *args, default=convert.msgpack, **kwargs): # type: ignore """Msgpack dump with preconversion for common unserializable types in place""" if isinstance(content, tuple): content = convert_namedtuple(content) return msgpack.dump(content, default=default, *args, **kwargs) def dumps(content, *args, default=convert.msgpack, **kwargs): # type: ignore """Msgpacks dump with preconversion for common unserializable types in place""" if isinstance(content, tuple): content = convert_namedtuple(content) return msgpack.dumps(content, default=default, *args, **kwargs) PKG NL2wpreconvert/output/simplejson.pyimport simplejson from funtools import partial from preconvert import convert from simplejson import * dumps = partial(simplejson.dumps, default=convert.json) # type: ignore dump = partial(simplejson.dump, default=convert.json) # type: ignore PK+LN+vAA"preconvert-0.0.2.dist-info/LICENSEThe MIT License (MIT) Copyright (c) 2019 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HPO preconvert-0.0.2.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UrPK!H =[#preconvert-0.0.2.dist-info/METADATAXmo_1u>H:Hc7uNs^AaҊ\I{&ݥe53$E9ε Trwv^yvfsD*]t1et!r9DҸ݋sac:jfHN,,c|D[ͭKI.$p,IaU&+'k\JKJ;](fq]rhn*ũ_.~xTltл4ކHBecƵo2ҎB$c:>:_E&Fn$T R*V͕'g,ʔNT"4ө.ږlK\^IY}x??i\0"UXT`KF*k=w+adK`x=XIr*66}?^Ψç~͙H2Wf+[v H k îR@ h%T4l YS e&H~)0uJ\RL 얥 -EY"1,i+u N*4̚U"#hyqK0YWL<|-ZʜBH^p輠(z/sVqZ奝U@?0neJ,2T:')1z|Hi8mXBӕ++s)trbp9{>pCfy˙u$mTh:]K kvmGF!`6%(aFi>s2GN>Н%'(SC5gcG _ґVMzyU r.&KPv̹#ڋ6&oe68(Hd}V@zb᫜^VfgqhG>ŃsCZf?~hC.qah\^~O-(' Ѧ?]*:L|'2Z#ۆ銢1wpouE/@C3՝?9bl|ppwׯ|x:jySwE/0X(hEfA SBgDlz6ŏƊ!s`Z5@UhV1ֺiŗ q 1&;NvݐK8tlC O)017z8(; PntϷ,x2``*}!vMSŲ ~.*T[JQ(O'^(tF MS˘N1xfMKU 'w7K0Eg0U:D[6Yj$ceH]nH3 "&O5jCD;--MMqKRDu $<3}A`rJςb`\oPG_=V?Wb1&?f<;)|:e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