cengal.text_processing.optional_formatter.versions.v_1.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, Tuple[Tuple[Any, ...], Dict[str, Any]], Any]]):
 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                elif isinstance(item_args_kwargs, tuple) and (2 == len(item_args_kwargs)) and isinstance(item_args_kwargs[0], tuple) and isinstance(item_args_kwargs[1], dict):
 63                    item_args, item_kwargs = arguments_per_item[item]
 64                else:
 65                    item_args = (item_args_kwargs,)
 66                    item_kwargs = dict()
 67                
 68                rendered_item = str()
 69                if is_first:
 70                    rendered_item += item_prefix
 71                else:
 72                    rendered_item += last_r_delimiter
 73                    rendered_item += item_l_delimiter
 74                
 75                last_r_delimiter = item_r_delimiter
 76                last_postfix = item_postfix
 77                rendered_item += item_template.format(*item_args, **item_kwargs)
 78                result += rendered_item
 79                if is_first:
 80                    is_first = False
 81                
 82        result += last_postfix
 83        return result
 84
 85
 86class OptionalFormatterHandy(OptionalFormatter):
 87    """
 88    template_per_item second tuple format:
 89    [left_delimiter(shown if not first), prefix(shown if first), template, postfix(shown if last), right_delimiter(shown if not last)]
 90
 91
 92    Example 1:
 93        f = OptionalFormatterHandy('hour', 'part_of_day', 'minute', 'second', 'millisecond',
 94                                   hour=IT('', '|(hours)', '{}', '|'),
 95                                   part_of_day=IT('-', '|(part_of_day)', '<{}.{second}>', '|'),
 96                                   minutes=IT(':', '|(minutes)', '{}', '|'),
 97                                   seconds=IT(':', '|(seconds)', '{}', '|'),
 98                                   millisecond=IT('.', '|(millisecond)', '{}', '|'))
 99
100        f(hour=4, minutes=15, seconds=54, millisecond=341)
101        >> |(hours)4:15:54.341|
102
103        f(seconds=54, minutes=15, hour=0, millisecond=0)
104        >> |(hours)0:15:54.0|
105
106        f(minutes=15, seconds=54)
107        >> |(minutes)15:54|
108
109        f(hour=4, part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
110        >> |(hours)4-<a.m>:15:54.341|
111
112        f(part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
113        >> |(part_of_day)<a.m>:15:54.341|
114
115        
116    Example 2:
117        f = OptionalFormatterHandy('hour', 'word', 'minute', 'second', 'millisecond',
118                                   hour=IT('', '|(hours)', '{}', '|'),
119                                   word=IT('', '|(word)', '-<"{}"-"{second}">-', '|'),
120                                   minutes=IT(':', '|(minutes)', '{}', '|'),
121                                   seconds=IT(':', '|(seconds)', '{}', '|'),
122                                   millisecond=IT('.', '|(millisecond)', '{}', '|'))
123
124        f(hour=4, minutes=15, seconds=54, millisecond=341)
125        >> |(hours)4:15:54.341|
126
127        f(seconds=54, minutes=15, hour=0, millisecond=0)
128        >> |(hours)0:15:54.0|
129
130        f(minutes=15, seconds=54)
131        >> |(minutes)15:54|
132
133        f(hour=4, word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
134        >> |(hours)4-<"HELLO!"-"WORLD!">-:15:54.341|
135
136        f(word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
137        >> |(word)-<"HELLO!"-"WORLD!">-:15:54.341|
138    """
139    def __init__(self, *item_positions: [str, ...], **template_per_item: [str, Union[IT, Tuple[str, str, str, str, str]]]):
140        super().__init__(item_positions, template_per_item)
141
142    def __call__(self, **arguments_per_item: [str, Union[AK, Tuple[Tuple[Any, ...], Dict[str, Any]], Any]]):
143        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, Tuple[Tuple[Any, ...], Dict[str, Any]], Any]]):
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                elif isinstance(item_args_kwargs, tuple) and (2 == len(item_args_kwargs)) and isinstance(item_args_kwargs[0], tuple) and isinstance(item_args_kwargs[1], dict):
64                    item_args, item_kwargs = arguments_per_item[item]
65                else:
66                    item_args = (item_args_kwargs,)
67                    item_kwargs = dict()
68                
69                rendered_item = str()
70                if is_first:
71                    rendered_item += item_prefix
72                else:
73                    rendered_item += last_r_delimiter
74                    rendered_item += item_l_delimiter
75                
76                last_r_delimiter = item_r_delimiter
77                last_postfix = item_postfix
78                rendered_item += item_template.format(*item_args, **item_kwargs)
79                result += rendered_item
80                if is_first:
81                    is_first = False
82                
83        result += last_postfix
84        return result
OptionalFormatter( item_positions: Tuple[Hashable, ...], template_per_item: Dict[Hashable, Union[ItemTemplate, 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):
 87class OptionalFormatterHandy(OptionalFormatter):
 88    """
 89    template_per_item second tuple format:
 90    [left_delimiter(shown if not first), prefix(shown if first), template, postfix(shown if last), right_delimiter(shown if not last)]
 91
 92
 93    Example 1:
 94        f = OptionalFormatterHandy('hour', 'part_of_day', 'minute', 'second', 'millisecond',
 95                                   hour=IT('', '|(hours)', '{}', '|'),
 96                                   part_of_day=IT('-', '|(part_of_day)', '<{}.{second}>', '|'),
 97                                   minutes=IT(':', '|(minutes)', '{}', '|'),
 98                                   seconds=IT(':', '|(seconds)', '{}', '|'),
 99                                   millisecond=IT('.', '|(millisecond)', '{}', '|'))
100
101        f(hour=4, minutes=15, seconds=54, millisecond=341)
102        >> |(hours)4:15:54.341|
103
104        f(seconds=54, minutes=15, hour=0, millisecond=0)
105        >> |(hours)0:15:54.0|
106
107        f(minutes=15, seconds=54)
108        >> |(minutes)15:54|
109
110        f(hour=4, part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
111        >> |(hours)4-<a.m>:15:54.341|
112
113        f(part_of_day=AK('a', second='m'), minutes=15, seconds=54, millisecond=341)
114        >> |(part_of_day)<a.m>:15:54.341|
115
116        
117    Example 2:
118        f = OptionalFormatterHandy('hour', 'word', 'minute', 'second', 'millisecond',
119                                   hour=IT('', '|(hours)', '{}', '|'),
120                                   word=IT('', '|(word)', '-<"{}"-"{second}">-', '|'),
121                                   minutes=IT(':', '|(minutes)', '{}', '|'),
122                                   seconds=IT(':', '|(seconds)', '{}', '|'),
123                                   millisecond=IT('.', '|(millisecond)', '{}', '|'))
124
125        f(hour=4, minutes=15, seconds=54, millisecond=341)
126        >> |(hours)4:15:54.341|
127
128        f(seconds=54, minutes=15, hour=0, millisecond=0)
129        >> |(hours)0:15:54.0|
130
131        f(minutes=15, seconds=54)
132        >> |(minutes)15:54|
133
134        f(hour=4, word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
135        >> |(hours)4-<"HELLO!"-"WORLD!">-:15:54.341|
136
137        f(word=AK('HELLO!', second='WORLD!'), minutes=15, seconds=54, millisecond=341)
138        >> |(word)-<"HELLO!"-"WORLD!">-:15:54.341|
139    """
140    def __init__(self, *item_positions: [str, ...], **template_per_item: [str, Union[IT, Tuple[str, str, str, str, str]]]):
141        super().__init__(item_positions, template_per_item)
142
143    def __call__(self, **arguments_per_item: [str, Union[AK, Tuple[Tuple[Any, ...], Dict[str, Any]], Any]]):
144        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=IT('', '|(hours)', '{}', '|'), word=IT('', '|(word)', '-<"{}"-"{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, 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]]])
140    def __init__(self, *item_positions: [str, ...], **template_per_item: [str, Union[IT, Tuple[str, str, str, str, str]]]):
141        super().__init__(item_positions, template_per_item)