Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Proposal for implementing frozendict in stdlib to cleanup implementing code that involves data mapping and conversions
"""
Proposal for implementing frozendict in stdlib to cleanup implementing code
that involves data mapping and conversions.
"""
from types import MappingProxyType
#####################################################
# Current way
#####################################################
DEFAULT_FIELD_MAP = MappingProxyType({
'a': 'A',
'b': 'B'
})
DEFAULT_PARSER_MAP = MappingProxyType({
'a': int,
'b': str
})
def passthrough(v):
return v
def convert(record, parsers=DEFAULT_PARSER_MAP, field_map=DEFAULT_FIELD_MAP,
transformers=MappingProxyType(dict())):
record = {k: parsers[k](v) for k, v in record.items()}
record = {field_map.get(k, k): v for k, v in record.items()}
record = {k: transformers.get(k, passthrough)(v) for k, v in record.items()}
return record
def example_convert():
record = {'a': '10', 'b': 'hello'}
custom_transformers = {'B': str.upper}
return convert(record, transformers=custom_transformers)
#####################################################
# Alternative way
#####################################################
# hypothetical for example
frozendict = dict
DEFAULT_FIELD_MAP = frozendict(a='A', b='B')
DEFAULT_PARSER_MAP = frozendict(a=int, b=str)
def frozen_convert(record, parsers=DEFAULT_PARSER_MAP, field_map=DEFAULT_FIELD_MAP,
transformers=frozendict()):
record = {k: parsers[k](v) for k, v in record.items()}
record = {field_map.get(k, k): v for k, v in record.items()}
record = {k: transformers.get(k, passthrough)(v) for k, v in record.items()}
return record
def example_frozen_convert():
record = {'a': '10', 'b': 'hello'}
custom_transformers = {'B': str.upper}
return convert(record, transformers=custom_transformers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment