cengal.text_processing.optional_formatter.versions.v_2.optional_formatter

  1#!/usr/bin/env python
  2# coding=utf-8
  3
  4# Copyright © 2012-2024 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space>
  5# 
  6# Licensed under the Apache License, Version 2.0 (the "License");
  7# you may not use this file except in compliance with the License.
  8# You may obtain a copy of the License at
  9# 
 10#     http://www.apache.org/licenses/LICENSE-2.0
 11# 
 12# Unless required by applicable law or agreed to in writing, software
 13# distributed under the License is distributed on an "AS IS" BASIS,
 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 15# See the License for the specific language governing permissions and
 16# limitations under the License.
 17
 18
 19from cengal.code_flow_control.args_manager import ArgsKwargs, AK
 20from collections import namedtuple
 21from typing import Hashable, Dict, Tuple, List, Any, AnyStr, Union, Sequence
 22
 23"""
 24Module Docstring
 25Docstrings: http://www.python.org/dev/peps/pep-0257/
 26"""
 27
 28__author__ = "ButenkoMS <gtalk@butenkoms.space>"
 29__copyright__ = "Copyright © 2012-2024 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space>"
 30__credits__ = ["ButenkoMS <gtalk@butenkoms.space>", ]
 31__license__ = "Apache License, Version 2.0"
 32__version__ = "4.4.1"
 33__maintainer__ = "ButenkoMS <gtalk@butenkoms.space>"
 34__email__ = "gtalk@butenkoms.space"
 35# __status__ = "Prototype"
 36__status__ = "Development"
 37# __status__ = "Production"
 38
 39
 40ItemTemplate = namedtuple("ItemTemplate", "l_delimiter, prefix, template, postfix, r_delimiter", defaults=('', '', '{}', '', ''))
 41IT = ItemTemplate
 42
 43
 44class OptionalFormatter:
 45    def __init__(self, item_positions: Tuple[Hashable, ...],
 46                 template_per_item: Dict[Hashable, Union[IT, Tuple[str, str, str, str, str]]]):
 47        self._item_positions = item_positions
 48        self._template_per_item = template_per_item
 49
 50    def __call__(self, arguments_per_item: Dict[Hashable, Union[AK, Any]]) -> str:
 51        result = str()
 52        is_first = True
 53        last_postfix = str()
 54        last_r_delimiter = str()
 55        for item in self._item_positions:
 56            if item in arguments_per_item:
 57                item_l_delimiter, item_prefix, item_template, item_postfix, item_r_delimiter = \
 58                    self._template_per_item[item]
 59                item_args_kwargs = arguments_per_item[item]
 60                if isinstance(item_args_kwargs, AK):
 61                    item_args, item_kwargs = arguments_per_item[item]()
 62                else:
 63                    item_args = (item_args_kwargs,)
 64                    item_kwargs = dict()
 65                
 66                rendered_item = str()
 67                if is_first:
 68                    rendered_item += item_prefix
 69                else:
 70                    rendered_item += last_r_delimiter
 71                    rendered_item += item_l_delimiter
 72                
 73                last_r_delimiter = item_r_delimiter
 74                last_postfix = item_postfix
 75                rendered_item += item_template.format(*item_args, **item_kwargs)
 76                result += rendered_item
 77                if is_first:
 78                    is_first = False
 79                
 80        result += last_postfix
 81        return result
 82
 83
 84class OptionalFormatterHandy(OptionalFormatter):
 85    """
 86    template_per_item second tuple format:
 87    [left_delimiter(shown if not first), prefix(shown if first), template, postfix(shown if last), right_delimiter(shown if not last)]
 88
 89
 90    Example 1:
 91        f = OptionalFormatterHandy('hour', 'part_of_day', 'minute', 'second', 'millisecond',
 92                                   hour=IT('', '|(hours)', '{}', '|'),
 93                                   part_of_day=IT('-', '|(part_of_day)', '<{}.{second}>', '|'),
 94                                   minutes=IT(':', '|(minutes)', '{}', '|'),
 95                                   seconds=IT(':', '|(seconds)', '{}', '|'),
 96                                   millisecond=IT('.', '|(millisecond)', '{}', '|'))
 97
 98        f(hour=4, minutes=15, seconds=54, millisecond=341)
 99        >> |(hours)4:15:54.341|
100
101        f(seconds=54, minutes=15, hour=0, millisecond=0)
102        >> |(hours)0:15:54.0|
103
104        f(minutes=15, seconds=54)
105        >> |(minutes)15:54|
106
107        f(hour=4, part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
108        >> |(hours)4-<a.m>:15:54.341|
109
110        f(part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
111        >> |(part_of_day)<a.m>:15:54.341|
112
113        
114    Example 2:
115        f = OptionalFormatterHandy('hour', 'word', 'minute', 'second', 'millisecond',
116                                   hour=('', '|(hours)', '{}', '|', ''),
117                                   word=('', '|(word)', '-<"{}"-"{second}">-', '|', ''),
118                                   minutes=(':', '|(minutes)', '{}', '|', ''),
119                                   seconds=(':', '|(seconds)', '{}', '|', ''),
120                                   millisecond=('.', '|(millisecond)', '{}', '|', ''))
121
122        f(hour=4, minutes=15, seconds=54, millisecond=341)
123        >> |(hours)4:15:54.341|
124
125        f(seconds=54, minutes=15, hour=0, millisecond=0)
126        >> |(hours)0:15:54.0|
127
128        f(minutes=15, seconds=54)
129        >> |(minutes)15:54|
130
131        f(hour=4, word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
132        >> |(hours)4-<"HELLO!"-"WORLD!">-:15:54.341|
133
134        f(word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
135        >> |(word)-<"HELLO!"-"WORLD!">-:15:54.341|
136    """
137    def __init__(self, *item_positions: [str, ...], **template_per_item: [str, Union[IT, Tuple[str, str, str, str, str]]]):
138        super().__init__(item_positions, template_per_item)
139
140    def __call__(self, **arguments_per_item: [str, Union[AK, Any]]) -> str:
141        return super(OptionalFormatterHandy, self).__call__(arguments_per_item)
class ItemTemplate(builtins.tuple):

ItemTemplate(l_delimiter, prefix, template, postfix, r_delimiter)

ItemTemplate(l_delimiter='', prefix='', template='{}', postfix='', r_delimiter='')

Create new instance of ItemTemplate(l_delimiter, prefix, template, postfix, r_delimiter)

l_delimiter

Alias for field number 0

prefix

Alias for field number 1

template

Alias for field number 2

postfix

Alias for field number 3

r_delimiter

Alias for field number 4

Inherited Members
builtins.tuple
index
count
IT = <class 'ItemTemplate'>
class OptionalFormatter:
45class OptionalFormatter:
46    def __init__(self, item_positions: Tuple[Hashable, ...],
47                 template_per_item: Dict[Hashable, Union[IT, Tuple[str, str, str, str, str]]]):
48        self._item_positions = item_positions
49        self._template_per_item = template_per_item
50
51    def __call__(self, arguments_per_item: Dict[Hashable, Union[AK, Any]]) -> str:
52        result = str()
53        is_first = True
54        last_postfix = str()
55        last_r_delimiter = str()
56        for item in self._item_positions:
57            if item in arguments_per_item:
58                item_l_delimiter, item_prefix, item_template, item_postfix, item_r_delimiter = \
59                    self._template_per_item[item]
60                item_args_kwargs = arguments_per_item[item]
61                if isinstance(item_args_kwargs, AK):
62                    item_args, item_kwargs = arguments_per_item[item]()
63                else:
64                    item_args = (item_args_kwargs,)
65                    item_kwargs = dict()
66                
67                rendered_item = str()
68                if is_first:
69                    rendered_item += item_prefix
70                else:
71                    rendered_item += last_r_delimiter
72                    rendered_item += item_l_delimiter
73                
74                last_r_delimiter = item_r_delimiter
75                last_postfix = item_postfix
76                rendered_item += item_template.format(*item_args, **item_kwargs)
77                result += rendered_item
78                if is_first:
79                    is_first = False
80                
81        result += last_postfix
82        return result
OptionalFormatter( item_positions: typing.Tuple[typing.Hashable, ...], template_per_item: typing.Dict[typing.Hashable, typing.Union[ItemTemplate, typing.Tuple[str, str, str, str, str]]])
46    def __init__(self, item_positions: Tuple[Hashable, ...],
47                 template_per_item: Dict[Hashable, Union[IT, Tuple[str, str, str, str, str]]]):
48        self._item_positions = item_positions
49        self._template_per_item = template_per_item
class OptionalFormatterHandy(OptionalFormatter):
 85class OptionalFormatterHandy(OptionalFormatter):
 86    """
 87    template_per_item second tuple format:
 88    [left_delimiter(shown if not first), prefix(shown if first), template, postfix(shown if last), right_delimiter(shown if not last)]
 89
 90
 91    Example 1:
 92        f = OptionalFormatterHandy('hour', 'part_of_day', 'minute', 'second', 'millisecond',
 93                                   hour=IT('', '|(hours)', '{}', '|'),
 94                                   part_of_day=IT('-', '|(part_of_day)', '<{}.{second}>', '|'),
 95                                   minutes=IT(':', '|(minutes)', '{}', '|'),
 96                                   seconds=IT(':', '|(seconds)', '{}', '|'),
 97                                   millisecond=IT('.', '|(millisecond)', '{}', '|'))
 98
 99        f(hour=4, minutes=15, seconds=54, millisecond=341)
100        >> |(hours)4:15:54.341|
101
102        f(seconds=54, minutes=15, hour=0, millisecond=0)
103        >> |(hours)0:15:54.0|
104
105        f(minutes=15, seconds=54)
106        >> |(minutes)15:54|
107
108        f(hour=4, part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
109        >> |(hours)4-<a.m>:15:54.341|
110
111        f(part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
112        >> |(part_of_day)<a.m>:15:54.341|
113
114        
115    Example 2:
116        f = OptionalFormatterHandy('hour', 'word', 'minute', 'second', 'millisecond',
117                                   hour=('', '|(hours)', '{}', '|', ''),
118                                   word=('', '|(word)', '-<"{}"-"{second}">-', '|', ''),
119                                   minutes=(':', '|(minutes)', '{}', '|', ''),
120                                   seconds=(':', '|(seconds)', '{}', '|', ''),
121                                   millisecond=('.', '|(millisecond)', '{}', '|', ''))
122
123        f(hour=4, minutes=15, seconds=54, millisecond=341)
124        >> |(hours)4:15:54.341|
125
126        f(seconds=54, minutes=15, hour=0, millisecond=0)
127        >> |(hours)0:15:54.0|
128
129        f(minutes=15, seconds=54)
130        >> |(minutes)15:54|
131
132        f(hour=4, word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
133        >> |(hours)4-<"HELLO!"-"WORLD!">-:15:54.341|
134
135        f(word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
136        >> |(word)-<"HELLO!"-"WORLD!">-:15:54.341|
137    """
138    def __init__(self, *item_positions: [str, ...], **template_per_item: [str, Union[IT, Tuple[str, str, str, str, str]]]):
139        super().__init__(item_positions, template_per_item)
140
141    def __call__(self, **arguments_per_item: [str, Union[AK, Any]]) -> str:
142        return super(OptionalFormatterHandy, self).__call__(arguments_per_item)

template_per_item second tuple format: [left_delimiter(shown if not first), prefix(shown if first), template, postfix(shown if last), right_delimiter(shown if not last)]

Example 1: f = OptionalFormatterHandy('hour', 'part_of_day', 'minute', 'second', 'millisecond', hour=IT('', '|(hours)', '{}', '|'), part_of_day=IT('-', '|(part_of_day)', '<{}.{second}>', '|'), minutes=IT(':', '|(minutes)', '{}', '|'), seconds=IT(':', '|(seconds)', '{}', '|'), millisecond=IT('.', '|(millisecond)', '{}', '|'))

f(hour=4, minutes=15, seconds=54, millisecond=341)
>> |(hours)4:15:54.341|

f(seconds=54, minutes=15, hour=0, millisecond=0)
>> |(hours)0:15:54.0|

f(minutes=15, seconds=54)
>> |(minutes)15:54|

f(hour=4, part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
>> |(hours)4-<a.m>:15:54.341|

f(part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
>> |(part_of_day)<a.m>:15:54.341|

Example 2: f = OptionalFormatterHandy('hour', 'word', 'minute', 'second', 'millisecond', hour=('', '|(hours)', '{}', '|', ''), word=('', '|(word)', '-<"{}"-"{second}">-', '|', ''), minutes=(':', '|(minutes)', '{}', '|', ''), seconds=(':', '|(seconds)', '{}', '|', ''), millisecond=('.', '|(millisecond)', '{}', '|', ''))

f(hour=4, minutes=15, seconds=54, millisecond=341)
>> |(hours)4:15:54.341|

f(seconds=54, minutes=15, hour=0, millisecond=0)
>> |(hours)0:15:54.0|

f(minutes=15, seconds=54)
>> |(minutes)15:54|

f(hour=4, word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
>> |(hours)4-<"HELLO!"-"WORLD!">-:15:54.341|

f(word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
>> |(word)-<"HELLO!"-"WORLD!">-:15:54.341|
OptionalFormatterHandy( *item_positions: [<class 'str'>, Ellipsis], **template_per_item: [<class 'str'>, typing.Union[ItemTemplate, typing.Tuple[str, str, str, str, str]]])
138    def __init__(self, *item_positions: [str, ...], **template_per_item: [str, Union[IT, Tuple[str, str, str, str, str]]]):
139        super().__init__(item_positions, template_per_item)