OwlMixin¶
Note
Usage on each methods are valid on the premise that the following classes is defined in advance.
# coding: utf-8
from owlmixin import OwlMixin, TOption
from owlmixin.owlcollections import TDict, TList
from owlmixin.owlenum import OwlEnum, OwlObjectEnum
class Animal(OwlObjectEnum): # pragma: no cover
DOG = ("dog", {"cry": "bow-wow"})
CAT = ("cat", {"cry": "mewing"})
def cry(self):
return self.object["cry"]
class Color(OwlEnum): # pragma: no cover
RED = "red"
GREEN = "green"
BLUE = "blue"
class Food(OwlMixin): # pragma: no cover
name: str
names_by_lang: TOption[TDict[str]]
class Human(OwlMixin): # pragma: no cover
id: int
name: str
favorites: TList[Food]
class Machine(OwlMixin): # pragma: no cover
id: int
name: str
class Japanese(OwlMixin): # pragma: no cover
name: str
language: str = "japanese"
- class owlmixin.OwlMixin[source]¶
- classmethod from_dict(d: dict, *, force_snake_case: bool = True, force_cast: bool = False, restrict: bool = True) T [source]¶
From dict to instance
- Parameters:
d – Dict
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Instance
Usage:
>>> from owlmixin.samples import Human, Food, Japanese >>> human: Human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].name 'Apple' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel'
You can use default value
>>> taro: Japanese = Japanese.from_dict({ ... "name": 'taro' ... }) >>> taro.name 'taro' >>> taro.language 'japanese'
If you don’t set force_snake=False explicitly, keys are transformed to snake case as following.
>>> human: Human = Human.from_dict({ ... "--id": 1, ... "<name>": "Tom", ... "favorites": [ ... {"name": "Apple", "namesByLang": {"en": "Apple"}} ... ] ... }) >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["en"] 'Apple'
You can allow extra parameters (like
hogehoge
) if you set restrict=False.>>> apple: Food = Food.from_dict({ ... "name": "Apple", ... "hogehoge": "ooooooooooooooooooooo", ... }, restrict=False) >>> apple.to_dict() {'name': 'Apple'}
You can prohibit extra parameters (like
hogehoge
) if you set restrict=True (which is default).>>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "hogehoge1": "ooooooooooooooooooooo", ... "hogehoge2": ["aaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiii"], ... "favorites": [ ... {"name": "Apple", "namesByLang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) Traceback (most recent call last): ... owlmixin.errors.UnknownPropertiesError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Unknown properties error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ `owlmixin.samples.Human` has unknown properties ['hogehoge1', 'hogehoge2']!! * If you want to allow unknown properties, set `restrict=False` * If you want to disallow unknown properties, add `hogehoge1` and `hogehoge2` to owlmixin.samples.Human
If you specify wrong type…
>>> human: Human = Human.from_dict({ ... "id": 1, ... "name": "ichiro", ... "favorites": ["apple", "orange"] ... }) Traceback (most recent call last): ... owlmixin.errors.InvalidTypeError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Invalid Type error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ `owlmixin.samples.Human#favorites.0 = apple` doesn't match expected types. Expected type is one of ["<class 'owlmixin.samples.Food'>", "<class 'dict'>"], but actual type is `<class 'str'>` * If you want to force cast, set `force_cast=True` * If you don't want to force cast, specify value which has correct type
If you don’t specify required params… (ex. name
>>> human: Human = Human.from_dict({ ... "id": 1 ... }) Traceback (most recent call last): ... owlmixin.errors.RequiredError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Required error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ `owlmixin.samples.Human#name: <class 'str'>` is empty!! * If `name` is certainly required, specify anything. * If `name` is optional, change type from `<class 'str'>` to `TOption[<class 'str'>]`
- classmethod from_optional_dict(d: Optional[dict], *, force_snake_case: bool = True, force_cast: bool = False, restrict: bool = True) TOption[T] [source]¶
From dict to optional instance.
- Parameters:
d – Dict
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Instance
Usage:
>>> from owlmixin.samples import Human >>> Human.from_optional_dict(None).is_none() True >>> Human.from_optional_dict({}).get() Traceback (most recent call last): ... owlmixin.errors.RequiredError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Required error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ `owlmixin.samples.Human#id: <class 'int'>` is empty!! * If `id` is certainly required, specify anything. * If `id` is optional, change type from `<class 'int'>` to `TOption[<class 'int'>]`
- classmethod from_dicts(ds: List[dict], *, force_snake_case: bool = True, force_cast: bool = False, restrict: bool = True) TList[T] [source]¶
From list of dict to list of instance
- Parameters:
ds – List of dict
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
List of instance
Usage:
>>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_dicts([ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]) >>> humans[0].name 'Tom' >>> humans[1].name 'John'
- classmethod from_iterable_dicts(ds: Iterable[dict], *, force_snake_case: bool = True, force_cast: bool = False, restrict: bool = True) TIterator[T] [source]¶
From iterable dict to iterable instance
- Parameters:
ds – Iterable dict
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Iterator
Usage:
>>> from owlmixin.samples import Human >>> humans: TIterator[Human] = Human.from_iterable_dicts([ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]) >>> humans.next_at(0).get().name 'Tom' >>> humans.next_at(0).get().name 'John'
- classmethod from_optional_dicts(ds: Optional[List[dict]], *, force_snake_case: bool = True, force_cast: bool = False, restrict: bool = True) TOption[TList[T]] [source]¶
From list of dict to optional list of instance.
- Parameters:
ds – List of dict
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
List of instance
Usage:
>>> from owlmixin.samples import Human >>> Human.from_optional_dicts(None).is_none() True >>> Human.from_optional_dicts([]).get() []
- classmethod from_optional_iterable_dicts(ds: Optional[Iterable[dict]], *, force_snake_case: bool = True, force_cast: bool = False, restrict: bool = True) TOption[TIterator[T]] [source]¶
From iterable dict to optional iterable instance.
- Parameters:
ds – Iterable dict
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Iterable instance
Usage:
>>> from owlmixin.samples import Human >>> Human.from_optional_dicts(None).is_none() True >>> Human.from_optional_dicts([]).get() []
- classmethod from_dicts_by_key(ds: dict, *, force_snake_case: bool = True, force_cast: bool = False, restrict: bool = True) TDict[T] [source]¶
From dict of dict to dict of instance
- Parameters:
ds – Dict of dict
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Dict of instance
Usage:
>>> from owlmixin.samples import Human >>> humans_by_name: TDict[Human] = Human.from_dicts_by_key({ ... 'Tom': {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... 'John': {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... }) >>> humans_by_name['Tom'].name 'Tom' >>> humans_by_name['John'].name 'John'
- classmethod from_optional_dicts_by_key(ds: Optional[dict], *, force_snake_case=True, force_cast: bool = False, restrict: bool = True) TOption[TDict[T]] [source]¶
From dict of dict to optional dict of instance.
- Parameters:
ds – Dict of dict
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Dict of instance
Usage:
>>> from owlmixin.samples import Human >>> Human.from_optional_dicts_by_key(None).is_none() True >>> Human.from_optional_dicts_by_key({}).get() {}
- classmethod from_json(data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = False) T [source]¶
From json string to instance
- Parameters:
data – Json string
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Instance
Usage:
>>> from owlmixin.samples import Human >>> human: Human = Human.from_json('''{ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }''') >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel'
- classmethod from_jsonf(fpath: str, encoding: str = 'utf8', *, force_snake_case=True, force_cast: bool = False, restrict: bool = False) T [source]¶
From json file path to instance
- Parameters:
fpath – Json file path
encoding – Json file encoding
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Instance
- classmethod from_json_to_list(data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = False) TList[T] [source]¶
From json string to list of instance
- Parameters:
data – Json string
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
List of instance
Usage:
>>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_json_to_list('''[ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]''') >>> humans[0].name 'Tom' >>> humans[1].name 'John'
- classmethod from_json_to_iterator(data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = False) TIterator[T] [source]¶
From json string to iterable instance
- Parameters:
data – Json string
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Iterable instance
Usage:
>>> from owlmixin.samples import Human >>> humans: TIterator[Human] = Human.from_json_to_iterator('''[ ... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]}, ... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]} ... ]''') >>> humans.next_at(1).get().name 'John' >>> humans.next_at(0).is_none() True
- classmethod from_jsonf_to_list(fpath: str, encoding: str = 'utf8', *, force_snake_case=True, force_cast: bool = False, restrict: bool = False) TList[T] [source]¶
From json file path to list of instance
- Parameters:
fpath – Json file path
encoding – Json file encoding
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
List of instance
- classmethod from_jsonf_to_iterator(fpath: str, encoding: str = 'utf8', *, force_snake_case=True, force_cast: bool = False, restrict: bool = False) TIterator[T] [source]¶
From json file path to iterable instance
- Parameters:
fpath – Json file path
encoding – Json file encoding
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Iterable instance
- classmethod from_yaml(data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = True) T [source]¶
From yaml string to instance
- Parameters:
data – Yaml string
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Instance
Usage:
>>> from owlmixin.samples import Human >>> human: Human = Human.from_yaml(''' ... id: 1 ... name: Tom ... favorites: ... - name: Apple ... names_by_lang: ... en: Apple ... de: Apfel ... - name: Orange ... ''') >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel'
- classmethod from_yamlf(fpath: str, encoding: str = 'utf8', *, force_snake_case=True, force_cast: bool = False, restrict: bool = True) T [source]¶
From yaml file path to instance
- Parameters:
fpath – Yaml file path
encoding – Yaml file encoding
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Instance
- classmethod from_yaml_to_list(data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = True) TList[T] [source]¶
From yaml string to list of instance
- Parameters:
data – Yaml string
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
List of instance
Usage:
>>> from owlmixin.samples import Human >>> humans: TList[Human] = Human.from_yaml_to_list(''' ... - id: 1 ... name: Tom ... favorites: ... - name: Apple ... - id: 2 ... name: John ... favorites: ... - name: Orange ... ''') >>> humans[0].name 'Tom' >>> humans[1].name 'John' >>> humans[0].favorites[0].name 'Apple'
- classmethod from_yaml_to_iterator(data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = True) TIterator[T] [source]¶
From yaml string to iterable instance
- Parameters:
data – Yaml string
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Iterable instance
Usage:
>>> from owlmixin.samples import Human >>> humans: TIterator[Human] = Human.from_yaml_to_iterator(''' ... - id: 1 ... name: Tom ... favorites: ... - name: Apple ... - id: 2 ... name: John ... favorites: ... - name: Orange ... ''') >>> human1 = humans.next_at(1).get() >>> human1.name 'John' >>> humans.next_at(0).is_none() True >>> human1.favorites[0].name 'Orange'
- classmethod from_yamlf_to_list(fpath: str, encoding: str = 'utf8', *, force_snake_case=True, force_cast: bool = False, restrict: bool = True) TList[T] [source]¶
From yaml file path to list of instance
- Parameters:
fpath – Yaml file path
encoding – Yaml file encoding
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
List of instance
- classmethod from_yamlf_to_iterator(fpath: str, encoding: str = 'utf8', *, force_snake_case=True, force_cast: bool = False, restrict: bool = True) TIterator[T] [source]¶
From yaml file path to iterable instance
- Parameters:
fpath – Yaml file path
encoding – Yaml file encoding
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Iterable instance
- classmethod from_csvf_to_list(fpath: str, fieldnames: Optional[Sequence[str]] = None, encoding: str = 'utf8', *, force_snake_case: bool = True, restrict: bool = True) TList[T] [source]¶
From csv file path to list of instance
- Parameters:
fpath – Csv file path
fieldnames – Specify csv header names if not included in the file
encoding – Csv file encoding
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
restrict – Prohibit extra parameters if True
- Returns:
List of Instance
- classmethod from_csvf_to_iterator(fpath: str, fieldnames: Optional[Sequence[str]] = None, encoding: str = 'utf8', *, force_snake_case: bool = True, restrict: bool = True) TIterator[T] [source]¶
From csv file path to iterable instance
- Parameters:
fpath – Csv file path
fieldnames – Specify csv header names if not included in the file
encoding – Csv file encoding
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
restrict – Prohibit extra parameters if True
- Returns:
Iterable Instance
- classmethod from_json_url(url: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = False) T [source]¶
From url which returns json to instance
- Parameters:
url – Url which returns json
force_snake_case – Keys are transformed to snake case in order to compliant PEP8 if True
force_cast – Cast forcibly if True
restrict – Prohibit extra parameters if True
- Returns:
Instance
- str_format(format_: str) str ¶
From instance to str with formatting
- Parameters:
format – format string
- Returns:
str
Usage:
>>> from owlmixin.samples import Human, Food >>> human_dict = { ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple"}} ... ] ... } >>> Human.from_dict(human_dict).str_format('{id}: {name}') '1: Tom'
- to_dict(*, ignore_none: bool = True, force_value: bool = True, ignore_empty: bool = False) dict ¶
From instance to dict
- Parameters:
ignore_none – Properties which is None are excluded if True
force_value – Transform to value using to_value (default: str()) of ValueTransformer which inherited if True
ignore_empty – Properties which is empty are excluded if True
- Returns:
Dict
- Usage:
>>> from owlmixin.samples import Human, Food >>> human_dict = { ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple"}} ... ] ... } >>> Human.from_dict(human_dict).to_dict() == human_dict True
You can include None properties by specifying False for ignore_none
>>> f = Food.from_dict({"name": "Apple"}).to_dict(ignore_none=False) >>> f["name"] 'Apple' >>> "names_by_lang" in f True >>> f["names_by_lang"]
As default
>>> f = Food.from_dict({"name": "Apple"}).to_dict() >>> f["name"] 'Apple' >>> "names_by_lang" in f False
You can exclude Empty properties by specifying True for ignore_empty
>>> f = Human.from_dict({"id": 1, "name": "Ichiro", "favorites": []}).to_dict() >>> f["favorites"] [] >>> f = Human.from_dict({"id": 1, "name": "Ichiro", "favorites": []}).to_dict(ignore_empty=True) >>> "favorites" in f False
- to_json(*, indent: int = None, ignore_none: bool = True, ignore_empty: bool = False) str ¶
From instance to json string
- Parameters:
indent – Number of indentation
ignore_none – Properties which is None are excluded if True
ignore_empty – Properties which is empty are excluded if True
- Returns:
Json string
Usage:
>>> from owlmixin.samples import Human >>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> human.to_json() '{"favorites": [{"name": "Apple","names_by_lang": {"de": "Apfel","en": "Apple"}},{"name": "Orange"}],"id": 1,"name": "Tom"}'
- to_jsonf(fpath: str, encoding: str = 'utf8', *, indent: int = None, ignore_none: bool = True, ignore_empty: bool = False) str ¶
From instance to json file
- Parameters:
fpath – Json file path
encoding – Json file encoding
indent – Number of indentation
ignore_none – Properties which is None are excluded if True
ignore_empty – Properties which is empty are excluded if True
- Returns:
Json file path
- to_pretty_json(*, ignore_none: bool = True, ignore_empty: bool = False) str ¶
From instance to pretty json string
- Parameters:
ignore_none – Properties which is None are excluded if True
ignore_empty – Properties which is empty are excluded if True
- Returns:
Json string
Usage:
>>> from owlmixin.samples import Human >>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> print(human.to_pretty_json()) { "favorites": [ { "name": "Apple", "names_by_lang": { "de": "Apfel", "en": "Apple" } }, { "name": "Orange" } ], "id": 1, "name": "Tom" }
- to_yaml(*, ignore_none: bool = True, ignore_empty: bool = False) str ¶
From instance to yaml string
- Parameters:
ignore_none – Properties which is None are excluded if True
ignore_empty – Properties which is empty are excluded if True
- Returns:
Yaml string
Usage:
>>> from owlmixin.samples import Human >>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> print(human.to_yaml()) favorites: - name: Apple names_by_lang: de: Apfel en: Apple - name: Orange id: 1 name: Tom
- to_yamlf(fpath: str, encoding: str = 'utf8', *, ignore_none: bool = True, ignore_empty: bool = False) str ¶
From instance to yaml file
- Parameters:
fpath – Yaml file path
encoding – Yaml file encoding
ignore_none – Properties which is None are excluded if True
ignore_empty – Properties which is empty are excluded if True
- Returns:
Yaml file path