mentortools/libs/: dict-caster-abm-1.1.52906a0 metadata and description

Simple index Stable version available

Filter, verify and cast dict items

author Mike Orlov
author_email m.orlov@abm-jsc.ru
classifiers
  • Programming Language :: Python :: 3
  • Programming Language :: Python :: 3.7
  • Programming Language :: Python :: 3.8
  • Programming Language :: Python :: 3.9
  • Programming Language :: Python :: 3.10
  • Programming Language :: Python :: 3.11
description_content_type text/markdown
requires_python >=3.7,<4.0
File Tox results History
dict_caster_abm-1.1.52906a0-py3-none-any.whl
Size
10 KB
Type
Python Wheel
Python
3
dict_caster_abm-1.1.52906a0.tar.gz
Size
8 KB
Type
Source

Dict Caster

Filter, verify and cast dict items

Usage examples 1:

from caster import Item, DictCaster

token, user, ids = DictCaster([
    Item("token", str),
    Item("user", str, optional=True),
    Item("ids", [int], default=[]),
]).cast_and_return({"token": 'test', "extra": "any"})
assert token == 'test'
assert user is None
assert ids == []

Usage examples 2:

from caster import Item, DictCaster

user_input = {
    "first_name": "Franz",
    "second_name": "Kafka",
    "age": "30",
    "extra": "...",
    "friend_ids": ["1", "2", "2"]
}

filtered_input = DictCaster([
    Item("first_name", str),
    Item("second_name", str, optional=True),
    Item("age", int),
    Item("friend_ids", {int})
]).cast(user_input)

print(filtered_input)
user_input = {
    "first_name": "Franz",
    "second_name": "Kafka",
    "age": 30,
    "friend_ids": {1, 2}
}
from typing import Any
from caster import Item, DictCaster

df = DictCaster(
    Item('test', int),
    Item('2nd', str, rename='second'),
    Item('boo', bool, optional=True),
    Item('foo', [int], default=[]),
    Item('some', Any, default=None),
    Item('log', None, optional=True, preprocessor=lambda x: print(x)),
)
res = df.cast({
    'test': '1',
    "2nd": 'foo',
    "boo": True,
    "foo": [1, 2.2, '3'],
    "some": int,
    'log': 'hi'
})
assert res == {
    'boo': True,
    'foo': [1, 2, 3],
    'log': None,
    'second': 'foo',
    'some': int,
    'test': 1
}

Support arguments with allowed None values: Optional[bool]

from typing import Optional
from dict_caster import DictCaster, Item

dc = DictCaster(Item("summary", Optional[bool]))
assert dc.cast_and_return({"summary": None}) == None
assert dc.cast_and_return({"summary": False}) == False
assert dc.cast_and_return({"summary": True}) == True

# raises 'required, but missing field: "summary"'
dc.cast_and_return({})