Collections

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"

TList

class owlmixin.owlcollections.TList(iterable=(), /)[source]
to_iterator() TIterator[T][source]

Usage:

>>> it = TList([1, 2, 3]).to_iterator()
>>> it.to_list()
[1, 2, 3]
>>> it.to_list()
[]
get(index: int) TOption[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).get(3)
Option --> 4
>>> TList([1, 2, 3, 4, 5]).get(5)
Option --> None
for_each(func: Callable[[T], None]) None[source]

Usage:

>>> TList([1, 2, 3]).for_each(lambda x: print(str(x)))
1
2
3
map(func: Callable[[T], U]) TList[U][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).map(lambda x: x+1)
[2, 3, 4, 5, 6]
emap(func: Callable[[T, int], U]) TList[U][source]
Usage:
>>> TList([10, 20, 30, 40, 50]).emap(lambda x, i: (x+1, i))
[(11, 0), (21, 1), (31, 2), (41, 3), (51, 4)]
flatten() TList[U][source]
Usage:
>>> TList([[1, 2], [3, 4]]).flatten()
[1, 2, 3, 4]
flat_map(func: Callable[[T], List[U]]) TList[U][source]
Usage:
>>> TList([1, 2, 3]).flat_map(lambda x: [x, x+1])
[1, 2, 2, 3, 3, 4]
filter(func: Callable[[T], bool]) TList[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).filter(lambda x: x > 3)
[4, 5]
reject(func: Callable[[T], bool]) TList[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).reject(lambda x: x > 3)
[1, 2, 3]
head() TOption[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).head()
Option --> 1
>>> TList([]).head()
Option --> None
take(size_: int) TList[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).take(3)
[1, 2, 3]
take_while(func: Callable[[T], bool]) TList[T][source]
Usage:
>>> TList([1, 2, 30, 4, 50]).take_while(lambda x: x < 10)
[1, 2]
tail(size_: int) TList[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).tail(3)
[3, 4, 5]
uniq() TList[T][source]
Usage:
>>> TList([1, 2, 3, 2, 1]).uniq()
[1, 2, 3]
uniq_by(func: Callable[[T], Any]) TList[T][source]
Usage:
>>> TList([1, 2, 3, -2, -1]).uniq_by(lambda x: x**2)
[1, 2, 3]
partition(func: Callable[[T], bool]) Tuple[TList[T], TList[T]][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).partition(lambda x: x > 3)
([1, 2, 3], [4, 5])
group_by(to_key: Callable[[T], str]) TDict[TList[T]][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).group_by(lambda x: x % 2).to_json()
'{"0": [2,4],"1": [1,3,5]}'
key_by(to_key: Callable[[T], str]) TDict[T][source]
Parameters:

to_key – value -> key

Usage:
>>> TList(['a1', 'b2', 'c3']).key_by(lambda x: x[0]).to_json()
'{"a": "a1","b": "b2","c": "c3"}'
>>> TList([1, 2, 3, 4, 5]).key_by(lambda x: x % 2).to_json()
'{"0": 4,"1": 5}'
order_by(func: Callable[[T], Any], reverse: bool = False) TList[T][source]
Usage:
>>> TList([12, 25, 31, 40, 57]).order_by(lambda x: x % 10)
[40, 31, 12, 25, 57]
>>> TList([12, 25, 31, 40, 57]).order_by(lambda x: x % 10, reverse=True)
[57, 25, 12, 31, 40]
concat(values: List[T], first: bool = False) TList[T][source]
Usage:
>>> TList([1, 2]).concat(TList([3, 4]))
[1, 2, 3, 4]
>>> TList([1, 2]).concat(TList([3, 4]), first=True)
[3, 4, 1, 2]
reduce(func: Callable[[U, T], U], init_value: U) U[source]
Usage:
>>> TList([1, 2, 3, 4, 5]).reduce(lambda t, x: t + 2*x, 100)
130
sum() Union[int, float][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).sum()
15
sum_by(func: Callable[[T], Union[int, float]]) Union[int, float][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).sum_by(lambda x: x*2)
30
count_by(func: Callable[[T], Any]) TDict[int][source]
Usage:
>>> TList([1, 11, 25, 35, 21, 4]).count_by(lambda x: x % 10)
{1: 3, 5: 2, 4: 1}
size() int[source]
Usage:
>>> TList([1, 2, 3, 4, 5]).size()
5
join(joint: str) str[source]
Usage:
>>> TList(['A', 'B', 'C']).join("-")
'A-B-C'
unlines(*, crlf: bool = False) str[source]
Usage:
>>> TList(['aaa', 'bbb', 'ccc']).unlines()
'aaa\nbbb\nccc'
>>> TList(['A', 'B', 'C']).unlines(crlf=True)
'A\r\nB\r\nC'
find(func: Callable[[T], bool]) TOption[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).find(lambda x: x > 3)
Option --> 4
>>> TList([1, 2, 3, 4, 5]).find(lambda x: x > 6)
Option --> None
all(func: Callable[[T], bool]) bool[source]
Usage:
>>> TList([1, 2, 3, 4, 5]).all(lambda x: x > 0)
True
>>> TList([1, 2, 3, 4, 5]).all(lambda x: x > 1)
False
any(func: Callable[[T], bool]) bool[source]
Usage:
>>> TList([1, 2, 3, 4, 5]).any(lambda x: x > 4)
True
>>> TList([1, 2, 3, 4, 5]).any(lambda x: x > 5)
False
intersection(values: List[T]) TList[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).intersection([2, 4, 6])
[2, 4]
not_intersection(values: List[T]) TList[T][source]
Usage:
>>> TList([1, 2, 3, 4, 5]).not_intersection([2, 4, 6])
[1, 3, 5]
to_csv(fieldnames: Sequence[str], *, with_header: bool = False, crlf: bool = False, tsv: bool = False) str

From sequence of text to csv string

Parameters:
  • fieldnames – Order of columns by property name

  • with_header – Add headers at the first line if True

  • crlf – Add CRLF line break at the end of line if True, else add LF

  • tsv – Use tabs as separator if True, else use comma

Returns:

Csv string

Usage:

>>> from owlmixin.samples import Human
>>> humans = Human.from_dicts([
...     {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
...     {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> print(humans.to_csv(fieldnames=['name', 'id', 'favorites']))
Tom,1,[{'name': 'Apple'}]
John,2,[{'name': 'Orange'}]
>>> print(humans.to_csv(fieldnames=['name', 'id', 'favorites'], with_header=True))
name,id,favorites
Tom,1,[{'name': 'Apple'}]
John,2,[{'name': 'Orange'}]
to_csvf(fpath: str, fieldnames: Sequence[str], *, encoding: str = 'utf8', with_header: bool = False, crlf: bool = False, tsv: bool = False) str

From instance to yaml file

Parameters:
  • fpath – Csv file path

  • fieldnames – Order of columns by property name

  • encoding – Csv file encoding

  • with_header – Add headers at the first line if True

  • crlf – Add CRLF line break at the end of line if True, else add LF

  • tsv – Use tabs as separator if True, else use comma

Returns:

Csv file path

to_dicts(*, ignore_none: bool = True, force_value: bool = True, ignore_empty: bool = False) List[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:

List[Dict]

Usage:

>>> from owlmixin.samples import Human, Food
>>> human_dicts = [
...     {
...         "id": 1,
...         "name": "Tom",
...         "favorites": [
...             {"name": "Apple", "names_by_lang": {"en": "Apple"}}
...         ]
...     },
...     {
...         "id": 2,
...         "name": "John",
...         "favorites": [
...             {"name": "Orange", "names_by_lang": {"en": "Orange"}}
...         ]
...     }
... ]
>>> Human.from_dicts(human_dicts).to_dicts() == human_dicts
True

You can include None properties by specifying False for ignore_none

>>> f = Food.from_dicts([{"name": "Apple"}]).to_dicts(ignore_none=False)
>>> f[0]["name"]
'Apple'
>>> "names_by_lang" in f[0]
True
>>> f[0]["names_by_lang"]

As default

>>> f = Food.from_dicts([{"name": "Apple"}]).to_dicts()
>>> f[0]["name"]
'Apple'
>>> "names_by_lang" in f[0]
False

You can exclude Empty properties by specifying True for ignore_empty

>>> f = Human.from_dicts([{"id": 1, "name": "Ichiro", "favorites": []}]).to_dicts()
>>> f[0]["favorites"]
[]
>>> f = Human.from_dicts([{"id": 1, "name": "Ichiro", "favorites": []}]).to_dicts(ignore_empty=True)
>>> "favorites" in f[0]
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_table(fieldnames: Sequence[str]) str

From sequence of text to csv string

Parameters:

fieldnames – Order of columns by property name

Returns:

Table string

Usage:

>>> from owlmixin.samples import Human
>>> humans = Human.from_dicts([
...     {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
...     {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> print(humans.to_table(fieldnames=['name', 'id', 'favorites']))
| name | id  |      favorites       |
| ---- | --- | -------------------- |
| Tom  | 1   | [{'name': 'Apple'}]  |
| John | 2   | [{'name': 'Orange'}] |
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

TIterator

class owlmixin.owlcollections.TIterator(iterable: Iterable)[source]
to_list() TList[T][source]

Usage:

>>> TIterator([1, 2, 3]).to_list()
[1, 2, 3]
next_at(index: int) TOption[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5])
>>> it.next_at(1)
Option --> 2
>>> it.next_at(1)
Option --> 4
>>> it.next_at(1)
Option --> None
for_each(func: Callable[[T], None]) None[source]

Usage:

>>> TIterator([1, 2, 3]).for_each(lambda x: print(str(x)))
1
2
3
map(func: Callable[[T], U]) TIterator[U][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5]).map(lambda x: x+1)
>>> it.to_list()
[2, 3, 4, 5, 6]
>>> it.to_list()
[]
emap(func: Callable[[T, int], U]) TIterator[U][source]

Usage:

>>> it = TIterator([10, 20, 30, 40, 50]).emap(lambda x, i: (x+1, i))
>>> it.to_list()
[(11, 0), (21, 1), (31, 2), (41, 3), (51, 4)]
>>> it.to_list()
[]
filter(func: Callable[[T], bool]) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5]).filter(lambda x: x > 3)
>>> it.to_list()
[4, 5]
>>> it.to_list()
[]
reject(func: Callable[[T], bool]) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5]).reject(lambda x: x > 3)
>>> it.to_list()
[1, 2, 3]
>>> it.to_list()
[]
flatten() TIterator[U][source]

Usage:

>>> it = TIterator([[1, 2], [3, 4]]).flatten()
>>> it.to_list()
[1, 2, 3, 4]
>>> it.to_list()
[]
flat_map(func: Callable[[T], List[U]]) TIterator[U][source]

Usage:

>>> it = TIterator([1, 2, 3]).flat_map(lambda x: [x, x+1])
>>> it.to_list()
[1, 2, 2, 3, 3, 4]
>>> it.to_list()
[]
head() TOption[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5])
>>> it.head().get()
1
>>> it.head().get()
2
take(size_: int) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5]).take(3)
>>> it.to_list()
[1, 2, 3]
>>> it.to_list()
[]
take_while(func: Callable[[T], bool]) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 30, 4, 50]).take_while(lambda x: x < 10)
>>> it.to_list()
[1, 2]
>>> it.to_list()
[]
tail(size_: int) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5]).tail(3)
>>> it.to_list()
[3, 4, 5]
>>> it.to_list()
[]
uniq() TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 2, 1]).uniq()
>>> it.to_list()
[1, 2, 3]
>>> it.to_list()
[]
uniq_by(func: Callable[[T], Any] = None) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 3, -2, -1]).uniq_by(lambda x: x**2)
>>> it.to_list()
[1, 2, 3]
>>> it.to_list()
[]
partition(func: Callable[[T], bool]) Tuple[TIterator[T], TIterator[T]][source]

Usage:

>>> ng, ok = TIterator([1, 2, 3, 4, 5]).partition(lambda x: x > 3)
>>> ng.to_list()
[1, 2, 3]
>>> ng.to_list()
[]
>>> ok.to_list()
[4, 5]
>>> ok.to_list()
[]
group_by(to_key: Callable[[T], str]) TDict[TList[T]][source]

Usage:

>>> TIterator([1, 2, 3, 4, 5]).group_by(lambda x: x % 2).to_json()
'{"0": [2,4],"1": [1,3,5]}'
key_by(to_key: Callable[[T], str]) TDict[T][source]
Parameters:

to_key – value -> key

Usage:

>>> TIterator(['a1', 'b2', 'c3']).key_by(lambda x: x[0]).to_json()
'{"a": "a1","b": "b2","c": "c3"}'
>>> TIterator([1, 2, 3, 4, 5]).key_by(lambda x: x % 2).to_json()
'{"0": 4,"1": 5}'
order_by(func: Callable[[T], Any], reverse: bool = False) TIterator[T][source]

Usage:

>>> it = TIterator([12, 25, 31, 40, 57]).order_by(lambda x: x % 10)
>>> it.to_list()
[40, 31, 12, 25, 57]
>>> it.to_list()
[]
>>> it = TIterator([12, 25, 31, 40, 57]).order_by(lambda x: x % 10, reverse=True)
>>> it.to_list()
[57, 25, 12, 31, 40]
>>> it.to_list()
[]
concat(values: Iterable[T], first: bool = False) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2]).concat(TIterator([3, 4]))
>>> it.to_list()
[1, 2, 3, 4]
>>> it.to_list()
[]
>>> it = TIterator([1, 2]).concat([3, 4], first=True)
>>> it.to_list()
[3, 4, 1, 2]
>>> it.to_list()
[]
reduce(func: Callable[[U, T], U], init_value: U) U[source]

Usage:

>>> TIterator([1, 2, 3, 4, 5]).reduce(lambda t, x: t + 2*x, 100)
130
sum() Union[int, float][source]

Usage:

>>> TIterator([1, 2, 3, 4, 5]).sum()
15
sum_by(func: Callable[[T], Union[int, float]]) Union[int, float][source]

Usage:

>>> TIterator([1, 2, 3, 4, 5]).sum_by(lambda x: x*2)
30
count_by(func: Callable[[T], Any]) TDict[int][source]
Usage:
>>> it = TIterator([1, 11, 25, 35, 21, 4])
>>> it.count_by(lambda x: x % 10)
{1: 3, 5: 2, 4: 1}
>>> it.to_list()
[]
join(joint: str) str[source]

Usage:

>>> TIterator(['A', 'B', 'C']).join("-")
'A-B-C'
unlines(*, crlf: bool = False) str[source]
Usage:
>>> TIterator(['aaa', 'bbb', 'ccc']).unlines()
'aaa\nbbb\nccc'
>>> TIterator(['A', 'B', 'C']).unlines(crlf=True)
'A\r\nB\r\nC'
find(func: Callable[[T], bool]) TOption[T][source]

Usage:

>>> TIterator([1, 2, 3, 4, 5]).find(lambda x: x > 3)
Option --> 4
>>> TIterator([1, 2, 3, 4, 5]).find(lambda x: x > 6)
Option --> None
all(func: Callable[[T], bool]) bool[source]

Usage:

>>> TIterator([1, 2, 3, 4, 5]).all(lambda x: x > 0)
True
>>> TIterator([1, 2, 3, 4, 5]).all(lambda x: x > 1)
False
any(func: Callable[[T], bool]) bool[source]

Usage:

>>> TIterator([1, 2, 3, 4, 5]).any(lambda x: x > 4)
True
>>> TIterator([1, 2, 3, 4, 5]).any(lambda x: x > 5)
False
intersection(values: Iterable[T]) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5]).intersection([2, 4, 6])
>>> it.to_list()
[2, 4]
>>> it.to_list()
[]
not_intersection(values: Iterable[T]) TIterator[T][source]

Usage:

>>> it = TIterator([1, 2, 3, 4, 5]).not_intersection([2, 4, 6])
>>> it.to_list()
[1, 3, 5]
>>> it.to_list()
[]
to_csv(fieldnames: Sequence[str], *, with_header: bool = False, crlf: bool = False, tsv: bool = False) str

From sequence of text to csv string

Parameters:
  • fieldnames – Order of columns by property name

  • with_header – Add headers at the first line if True

  • crlf – Add CRLF line break at the end of line if True, else add LF

  • tsv – Use tabs as separator if True, else use comma

Returns:

Csv string

Usage:

>>> from owlmixin.samples import Human
>>> humans = Human.from_dicts([
...     {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
...     {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> print(humans.to_csv(fieldnames=['name', 'id', 'favorites']))
Tom,1,[{'name': 'Apple'}]
John,2,[{'name': 'Orange'}]
>>> print(humans.to_csv(fieldnames=['name', 'id', 'favorites'], with_header=True))
name,id,favorites
Tom,1,[{'name': 'Apple'}]
John,2,[{'name': 'Orange'}]
to_csvf(fpath: str, fieldnames: Sequence[str], *, encoding: str = 'utf8', with_header: bool = False, crlf: bool = False, tsv: bool = False) str

From instance to yaml file

Parameters:
  • fpath – Csv file path

  • fieldnames – Order of columns by property name

  • encoding – Csv file encoding

  • with_header – Add headers at the first line if True

  • crlf – Add CRLF line break at the end of line if True, else add LF

  • tsv – Use tabs as separator if True, else use comma

Returns:

Csv file path

to_dicts(*, ignore_none: bool = True, force_value: bool = True, ignore_empty: bool = False) List[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:

List[Dict]

Usage:

>>> from owlmixin.samples import Human, Food
>>> human_dicts = [
...     {
...         "id": 1,
...         "name": "Tom",
...         "favorites": [
...             {"name": "Apple", "names_by_lang": {"en": "Apple"}}
...         ]
...     },
...     {
...         "id": 2,
...         "name": "John",
...         "favorites": [
...             {"name": "Orange", "names_by_lang": {"en": "Orange"}}
...         ]
...     }
... ]
>>> Human.from_dicts(human_dicts).to_dicts() == human_dicts
True

You can include None properties by specifying False for ignore_none

>>> f = Food.from_dicts([{"name": "Apple"}]).to_dicts(ignore_none=False)
>>> f[0]["name"]
'Apple'
>>> "names_by_lang" in f[0]
True
>>> f[0]["names_by_lang"]

As default

>>> f = Food.from_dicts([{"name": "Apple"}]).to_dicts()
>>> f[0]["name"]
'Apple'
>>> "names_by_lang" in f[0]
False

You can exclude Empty properties by specifying True for ignore_empty

>>> f = Human.from_dicts([{"id": 1, "name": "Ichiro", "favorites": []}]).to_dicts()
>>> f[0]["favorites"]
[]
>>> f = Human.from_dicts([{"id": 1, "name": "Ichiro", "favorites": []}]).to_dicts(ignore_empty=True)
>>> "favorites" in f[0]
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_table(fieldnames: Sequence[str]) str

From sequence of text to csv string

Parameters:

fieldnames – Order of columns by property name

Returns:

Table string

Usage:

>>> from owlmixin.samples import Human
>>> humans = Human.from_dicts([
...     {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
...     {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> print(humans.to_table(fieldnames=['name', 'id', 'favorites']))
| name | id  |      favorites       |
| ---- | --- | -------------------- |
| Tom  | 1   | [{'name': 'Apple'}]  |
| John | 2   | [{'name': 'Orange'}] |
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

TDict

class owlmixin.owlcollections.TDict[source]
map(func: Callable[[K, T], U]) TIterator[U][source]

Usage:

>>> it = TDict(k1=1, k2=2, k3=3).map(lambda k, v: v*2)
>>> sorted(it.to_list())
[2, 4, 6]
>>> it.to_list()
[]
map_values(func: Callable[[T], U]) TDict[U][source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).map_values(lambda x: x*2) == {
...     "k1": 2,
...     "k2": 4,
...     "k3": 6
... }
True
map_values2(func: Callable[[K, T], U]) TDict[U][source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).map_values2(lambda k, v: f'{k} -> {v*2}') == {
...     "k1": "k1 -> 2",
...     "k2": "k2 -> 4",
...     "k3": "k3 -> 6"
... }
True
filter(func: Callable[[K, T], bool]) TIterator[T][source]

Usage:

>>> it = TDict(k1=1, k2=2, k3=3).filter(lambda k, v: v < 2)
>>> it.to_list()
[1]
>>> it.to_list()
[]
reject(func: Callable[[K, T], bool]) TIterator[T][source]

Usage:

>>> it = TDict(k1=1, k2=2, k3=3).reject(lambda k, v: v < 3)
>>> it.to_list()
[3]
>>> it.to_list()
[]
sum() Union[int, float][source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).sum()
6
sum_by(func: Callable[[K, T], Union[int, float]]) Union[int, float][source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).sum_by(lambda k, v: v*2)
12
size() int[source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).size()
3
find(func: Callable[[K, T], bool]) TOption[T][source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).find(lambda k, v: v == 2)
Option --> 2
>>> TDict(k1=1, k2=2, k3=3).find(lambda k, v: v == 4)
Option --> None
to_list() TList[T][source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).to_list().order_by(lambda x: x)
[1, 2, 3]
to_iterator() TIterator[T][source]

Usage:

>>> it = TDict(k1=1, k2=2, k3=3).to_iterator().order_by(lambda x: x)
>>> it.to_list()
[1, 2, 3]
>>> it.to_list()
[]
all(func: Callable[[K, T], bool]) bool[source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 0)
True
>>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 1)
False
any(func: Callable[[K, T], bool]) bool[source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 2)
True
>>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 3)
False
assign(dict_: Dict[str, T]) TDict[T][source]

Usage:

>>> TDict(k1=1, k2=2).assign({'k3': 3})
{'k1': 1, 'k2': 2, 'k3': 3}
>>> TDict(k1=1, k2=2).assign(TDict({'k2': 3}))
{'k1': 1, 'k2': 3}
pick_by(func: Callable[[K, T], bool]) TDict[T][source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).pick_by(lambda k, v: v > 2)
{'k3': 3}
omit_by(func: Callable[[K, T], bool]) TDict[T][source]

Usage:

>>> TDict(k1=1, k2=2, k3=3).omit_by(lambda k, v: v > 2)
{'k1': 1, 'k2': 2}
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