Skip to content

path_templates

DefaultKeysDict

Bases: dict

Dictionary that supports the default key to use for str conversion.

Is helpful for changes of a key in a template from string to dictionary for example '{folder}' -> '{folder[name]}'. >>> data = DefaultKeysDict( >>> "name", >>> {"folder": {"name": "FolderName"}} >>> ) >>> print("{folder[name]}".format_map(data)) FolderName >>> print("{folder}".format_map(data)) FolderName

Parameters:

Name Type Description Default
default_key Union[str, Iterable[str]]

Default key to use for str conversion. Can also expect multiple keys for more nested dictionary.

required
Source code in client/ayon_core/lib/path_templates.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class DefaultKeysDict(dict):
    """Dictionary that supports the default key to use for str conversion.

    Is helpful for changes of a key in a template from string to dictionary
        for example '{folder}' -> '{folder[name]}'.
        >>> data = DefaultKeysDict(
        >>>     "name",
        >>>     {"folder": {"name": "FolderName"}}
        >>> )
        >>> print("{folder[name]}".format_map(data))
        FolderName
        >>> print("{folder}".format_map(data))
        FolderName

    Args:
        default_key (Union[str, Iterable[str]]): Default key to use for str
            conversion. Can also expect multiple keys for more nested
            dictionary.

    """
    def __init__(
        self, default_keys: Union[str, Iterable[str]], *args, **kwargs
    ) -> None:
        if isinstance(default_keys, str):
            default_keys = [default_keys]
        else:
            default_keys = list(default_keys)
        if not default_keys:
            raise ValueError(
                "Default key must be set. Got empty default keys."
            )

        self._default_keys = default_keys
        super().__init__(*args, **kwargs)

    def __str__(self) -> str:
        return str(self.get_default_value())

    def get_default_keys(self) -> list[str]:
        return list(self._default_keys)

    def get_default_value(self) -> Any:
        value = self
        for key in self._default_keys:
            value = value[key]
        return value

FormatObject

Object that can be used for formatting.

This is base that is valid for to be used in 'StringTemplate' value.

Source code in client/ayon_core/lib/path_templates.py
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
class FormatObject:
    """Object that can be used for formatting.

    This is base that is valid for to be used in 'StringTemplate' value.
    """
    def __init__(self):
        self.value = ""

    def __format__(self, *args, **kwargs):
        return self.value.__format__(*args, **kwargs)

    def __str__(self) -> str:
        return str(self.value)

    def __repr__(self) -> str:
        return self.__str__()

FormattingPart

String with formatting template.

Containt only single key to format e.g. "{project[name]}".

Parameters:

Name Type Description Default
field_name str

Name of key.

required
format_spec str

Format specification.

required
conversion Union[str, None]

Conversion type.

required
Source code in client/ayon_core/lib/path_templates.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
class FormattingPart:
    """String with formatting template.

    Containt only single key to format e.g. "{project[name]}".

    Args:
        field_name (str): Name of key.
        format_spec (str): Format specification.
        conversion (Union[str, None]): Conversion type.

    """
    def __init__(
        self,
        field_name: str,
        format_spec: str,
        conversion: Union[str, None],
    ):
        format_spec_v = ""
        if format_spec:
            format_spec_v = f":{format_spec}"
        conversion_v = ""
        if conversion:
            conversion_v = f"!{conversion}"

        self._field_name: str = field_name
        self._format_spec: str = format_spec_v
        self._conversion: str = conversion_v

        template_base = f"{field_name}{format_spec_v}{conversion_v}"
        self._template_base: str = template_base
        self._template: str = f"{{{template_base}}}"

    @property
    def template(self) -> str:
        return self._template

    def __repr__(self) -> str:
        return "<Format:{}>".format(self._template)

    def __str__(self) -> str:
        return self._template

    @staticmethod
    def validate_value_type(value: Any) -> bool:
        """Check if value can be used for formatting of single key."""
        if isinstance(value, (numbers.Number, FormatObject)):
            return True

        for inh_class in type(value).mro():
            if inh_class is str:
                return True
        return False

    @staticmethod
    def validate_key_is_matched(key: str) -> bool:
        """Validate that opening has closing at correct place.
        Future-proof, only square brackets are currently used in keys.

        Example:
            >>> is_matched("[]()()(((([])))")
            False
            >>> is_matched("[](){{{[]}}}")
            True

        Returns:
            bool: Openings and closing are valid.

        """
        mapping = dict(zip("({[", ")}]"))
        opening = set(mapping.keys())
        closing = set(mapping.values())
        queue = []

        for letter in key:
            if letter in opening:
                queue.append(mapping[letter])
            elif letter in closing:
                if not queue or letter != queue.pop():
                    return False
        return not queue

    @staticmethod
    def keys_to_template_base(keys: list[str]):
        if not keys:
            return None
        # Create copy of keys
        keys = list(keys)
        template_base = keys.pop(0)
        joined_keys = "".join([f"[{key}]" for key in keys])
        return f"{template_base}{joined_keys}"

    def keys(self) -> tuple[str]:
        """Return keys of the template.

        Returns:
            tuple[str]: Keys of the template.

        """
        return tuple(SUB_DICT_PATTERN.findall(self._field_name))

    def format(
        self, data: dict[str, Any], result: TemplatePartResult
    ) -> TemplatePartResult:
        """Format the formattings string.

        Args:
            data(dict): Data that should be used for formatting.
            result(TemplatePartResult): Object where result is stored.

        """
        key = self._template_base

        # ensure key is properly formed [({})] properly closed.
        if not self.validate_key_is_matched(key):
            result.add_missing_key(key)
            result.add_output(self.template)
            return result

        # check if key expects subdictionary keys (e.g. project[name])
        key_subdict = self.keys()

        value = data
        missing_key = False
        invalid_type = False
        used_keys = []
        keys_to_value = None
        used_value = None

        for sub_key in key_subdict:
            if isinstance(value, list):
                if not sub_key.lstrip("-").isdigit():
                    invalid_type = True
                    break
                sub_key = int(sub_key)
                if sub_key < 0:
                    sub_key = len(value) + sub_key

                valid = 0 <= sub_key < len(value)
                if not valid:
                    used_keys.append(sub_key)
                    missing_key = True
                    break

                used_keys.append(sub_key)
                if keys_to_value is None:
                    keys_to_value = list(used_keys)
                    keys_to_value.pop(-1)
                    used_value = copy.deepcopy(value)
                value = value[sub_key]
                continue

            if (
                value is None
                or (hasattr(value, "items") and sub_key not in value)
            ):
                missing_key = True
                used_keys.append(sub_key)
                break

            if not hasattr(value, "items"):
                invalid_type = True
                break

            used_keys.append(sub_key)
            value = value.get(sub_key)

        field_name = key_subdict[0]
        if used_keys:
            field_name = self.keys_to_template_base(used_keys)

        if missing_key or invalid_type:
            if missing_key:
                result.add_missing_key(field_name)

            elif invalid_type:
                result.add_invalid_type(field_name, value)

            result.add_output(self.template)
            return result

        if isinstance(value, DefaultKeysDict):
            try:
                value = value.get_default_value()
            except KeyError:
                pass

        if not self.validate_value_type(value):
            result.add_invalid_type(key, value)
            result.add_output(self.template)
            return result

        fill_data = root_fill_data = {}
        parent_fill_data = None
        parent_key = None
        fill_value = data
        value_filled = False
        for used_key in used_keys:
            if isinstance(fill_value, list):
                parent_fill_data[parent_key] = fill_value
                value_filled = True
                break
            fill_value = fill_value[used_key]
            parent_fill_data = fill_data
            fill_data = parent_fill_data.setdefault(used_key, {})
            parent_key = used_key

        if not value_filled:
            parent_fill_data[used_keys[-1]] = value

        template = f"{{{field_name}{self._format_spec}{self._conversion}}}"
        formatted_value = template.format(**root_fill_data)
        used_key = key
        if keys_to_value is not None:
            used_key = self.keys_to_template_base(keys_to_value)

        if used_value is None:
            if isinstance(value, numbers.Number):
                used_value = value
            else:
                used_value = formatted_value
        result.add_really_used_value(self._field_name, used_value)
        result.add_used_value(used_key, used_value)
        result.add_output(formatted_value)
        return result

format(data, result)

Format the formattings string.

Parameters:

Name Type Description Default
data dict

Data that should be used for formatting.

required
result TemplatePartResult

Object where result is stored.

required
Source code in client/ayon_core/lib/path_templates.py
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
def format(
    self, data: dict[str, Any], result: TemplatePartResult
) -> TemplatePartResult:
    """Format the formattings string.

    Args:
        data(dict): Data that should be used for formatting.
        result(TemplatePartResult): Object where result is stored.

    """
    key = self._template_base

    # ensure key is properly formed [({})] properly closed.
    if not self.validate_key_is_matched(key):
        result.add_missing_key(key)
        result.add_output(self.template)
        return result

    # check if key expects subdictionary keys (e.g. project[name])
    key_subdict = self.keys()

    value = data
    missing_key = False
    invalid_type = False
    used_keys = []
    keys_to_value = None
    used_value = None

    for sub_key in key_subdict:
        if isinstance(value, list):
            if not sub_key.lstrip("-").isdigit():
                invalid_type = True
                break
            sub_key = int(sub_key)
            if sub_key < 0:
                sub_key = len(value) + sub_key

            valid = 0 <= sub_key < len(value)
            if not valid:
                used_keys.append(sub_key)
                missing_key = True
                break

            used_keys.append(sub_key)
            if keys_to_value is None:
                keys_to_value = list(used_keys)
                keys_to_value.pop(-1)
                used_value = copy.deepcopy(value)
            value = value[sub_key]
            continue

        if (
            value is None
            or (hasattr(value, "items") and sub_key not in value)
        ):
            missing_key = True
            used_keys.append(sub_key)
            break

        if not hasattr(value, "items"):
            invalid_type = True
            break

        used_keys.append(sub_key)
        value = value.get(sub_key)

    field_name = key_subdict[0]
    if used_keys:
        field_name = self.keys_to_template_base(used_keys)

    if missing_key or invalid_type:
        if missing_key:
            result.add_missing_key(field_name)

        elif invalid_type:
            result.add_invalid_type(field_name, value)

        result.add_output(self.template)
        return result

    if isinstance(value, DefaultKeysDict):
        try:
            value = value.get_default_value()
        except KeyError:
            pass

    if not self.validate_value_type(value):
        result.add_invalid_type(key, value)
        result.add_output(self.template)
        return result

    fill_data = root_fill_data = {}
    parent_fill_data = None
    parent_key = None
    fill_value = data
    value_filled = False
    for used_key in used_keys:
        if isinstance(fill_value, list):
            parent_fill_data[parent_key] = fill_value
            value_filled = True
            break
        fill_value = fill_value[used_key]
        parent_fill_data = fill_data
        fill_data = parent_fill_data.setdefault(used_key, {})
        parent_key = used_key

    if not value_filled:
        parent_fill_data[used_keys[-1]] = value

    template = f"{{{field_name}{self._format_spec}{self._conversion}}}"
    formatted_value = template.format(**root_fill_data)
    used_key = key
    if keys_to_value is not None:
        used_key = self.keys_to_template_base(keys_to_value)

    if used_value is None:
        if isinstance(value, numbers.Number):
            used_value = value
        else:
            used_value = formatted_value
    result.add_really_used_value(self._field_name, used_value)
    result.add_used_value(used_key, used_value)
    result.add_output(formatted_value)
    return result

keys()

Return keys of the template.

Returns:

Type Description
tuple[str]

tuple[str]: Keys of the template.

Source code in client/ayon_core/lib/path_templates.py
644
645
646
647
648
649
650
651
def keys(self) -> tuple[str]:
    """Return keys of the template.

    Returns:
        tuple[str]: Keys of the template.

    """
    return tuple(SUB_DICT_PATTERN.findall(self._field_name))

validate_key_is_matched(key) staticmethod

Validate that opening has closing at correct place. Future-proof, only square brackets are currently used in keys.

Example

is_matched("()(((([])))") False is_matched("{{{[]}}}") True

Returns:

Name Type Description
bool bool

Openings and closing are valid.

Source code in client/ayon_core/lib/path_templates.py
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
@staticmethod
def validate_key_is_matched(key: str) -> bool:
    """Validate that opening has closing at correct place.
    Future-proof, only square brackets are currently used in keys.

    Example:
        >>> is_matched("[]()()(((([])))")
        False
        >>> is_matched("[](){{{[]}}}")
        True

    Returns:
        bool: Openings and closing are valid.

    """
    mapping = dict(zip("({[", ")}]"))
    opening = set(mapping.keys())
    closing = set(mapping.values())
    queue = []

    for letter in key:
        if letter in opening:
            queue.append(mapping[letter])
        elif letter in closing:
            if not queue or letter != queue.pop():
                return False
    return not queue

validate_value_type(value) staticmethod

Check if value can be used for formatting of single key.

Source code in client/ayon_core/lib/path_templates.py
595
596
597
598
599
600
601
602
603
604
@staticmethod
def validate_value_type(value: Any) -> bool:
    """Check if value can be used for formatting of single key."""
    if isinstance(value, (numbers.Number, FormatObject)):
        return True

    for inh_class in type(value).mro():
        if inh_class is str:
            return True
    return False

OptionalPart

Template part which contains optional formatting strings.

If this part can't be filled the result is empty string.

Parameters:

Name Type Description Default
parts list

Parts of template. Can contain 'str', 'OptionalPart' or 'FormattingPart'.

required
Source code in client/ayon_core/lib/path_templates.py
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
class OptionalPart:
    """Template part which contains optional formatting strings.

    If this part can't be filled the result is empty string.

    Args:
        parts(list): Parts of template. Can contain 'str', 'OptionalPart' or
            'FormattingPart'.
    """

    def __init__(
        self,
        parts: list[Union[str, OptionalPart, FormattingPart]]
    ):
        self._parts: list[Union[str, OptionalPart, FormattingPart]] = parts

    @property
    def parts(self) -> list[Union[str, OptionalPart, FormattingPart]]:
        return self._parts

    def remove_optional_parts_for_data(self, data: dict[str, Any]) -> str:
        if not data:
            return ""

        output = ""
        for part in self._parts:
            if isinstance(part, str):
                output += part
            elif isinstance(part, OptionalPart):
                output += part.remove_optional_parts_for_data(data)

            elif isinstance(part, FormattingPart):
                data_v = data
                for key in part.keys():
                    if key not in data_v:
                        return ""
                    try:
                        data_v = data_v[key]
                    except (KeyError, IndexError, TypeError):
                        return ""
                output += part.template

            else:
                raise TypeError(
                    f"Got invalid type in template parts '{type(part)}'"
                )
        return output

    def __str__(self) -> str:
        joined_parts = "".join([str(p) for p in self._parts])
        return f"<{joined_parts}>"

    def __repr__(self) -> str:
        joined_parts = "".join([str(p) for p in self._parts])
        return f"<Optional:{joined_parts}>"

    def format(
        self,
        data: dict[str, Any],
        result: TemplatePartResult,
    ) -> TemplatePartResult:
        new_result = TemplatePartResult(True)
        for part in self._parts:
            if isinstance(part, str):
                new_result.add_output(part)
            else:
                part.format(data, new_result)

        if new_result.solved:
            result.add_output(new_result)
        return result

StringTemplate

String that can be formatted.

Source code in client/ayon_core/lib/path_templates.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
class StringTemplate:
    """String that can be formatted."""
    def __init__(self, template: str):
        if not isinstance(template, str):
            raise TypeError(
                f"<{self.__class__.__name__}> argument must be a string,"
                f" not {str(type(template))}."
            )

        self._template: str = template
        parts = []
        formatter = Formatter()

        for item in formatter.parse(template):
            literal_text, field_name, format_spec, conversion = item
            if literal_text:
                parts.append(literal_text)
            if field_name:
                parts.append(
                    FormattingPart(field_name, format_spec, conversion)
                )

        new_parts = []
        for part in parts:
            if not isinstance(part, str):
                new_parts.append(part)
                continue

            substr = ""
            for char in part:
                if char not in ("<", ">"):
                    substr += char
                else:
                    if substr:
                        new_parts.append(substr)
                    new_parts.append(char)
                    substr = ""
            if substr:
                new_parts.append(substr)

        self._parts: list[Union[str, OptionalPart, FormattingPart]] = (
            self.find_optional_parts(new_parts)
        )

    def __str__(self) -> str:
        return self.template

    def __repr__(self) -> str:
        return f"<{self.__class__.__name__}> {self.template}"

    def __contains__(self, other: str) -> bool:
        return other in self.template

    def replace(self, *args, **kwargs):
        self._template = self.template.replace(*args, **kwargs)
        return self

    @property
    def template(self) -> str:
        return self._template

    def format(self, data: dict[str, Any]) -> "TemplateResult":
        """ Figure out with whole formatting.

        Separate advanced keys (*Like '{project[name]}') from string which must
        be formatted separately in case of missing or incomplete keys in data.

        Args:
            data (dict): Containing keys to be filled into template.

        Returns:
            TemplateResult: Filled or partially filled template containing all
                data needed or missing for filling template.

        """
        result = TemplatePartResult()
        for part in self._parts:
            if isinstance(part, str):
                result.add_output(part)
            else:
                part.format(data, result)

        invalid_types = result.invalid_types
        invalid_types.update(result.invalid_optional_types)
        invalid_types = result.split_keys_to_subdicts(invalid_types)

        missing_keys = result.missing_keys
        missing_keys |= result.missing_optional_keys

        solved = result.solved
        used_values = result.get_clean_used_values()

        return TemplateResult(
            result.output,
            self.template,
            solved,
            used_values,
            missing_keys,
            invalid_types
        )

    def format_strict(self, data: dict[str, Any]) -> "TemplateResult":
        result = self.format(data)
        result.validate()
        return result

    def remove_optional_parts_for_data(
        self,
        data: Optional[dict[str, Any]] = None,
    ) -> str:
        """Remove optional parts from template for data.

        This method does not modify the template object itself.

        Note:
            At this moment the functionality is not 1:1 with 'format' where
                lists are supported and the values are validated.

        Args:
            data (Optional[dict[str, Any]]): Template data for template.

        Returns:
            str: Template without optional parts that are not available
                in passed data.

        """
        if data is None:
            data = {}

        output = ""
        for part in self._parts:
            if isinstance(part, str):
                output += part
            elif isinstance(part, FormattingPart):
                output += part.template
            elif isinstance(part, OptionalPart):
                output += part.remove_optional_parts_for_data(data)
            else:
                raise TypeError(
                    f"Got invalid type in template parts '{type(part)}'"
                )
        return output

    @classmethod
    def format_template(
        cls, template: str, data: dict[str, Any]
    ) -> "TemplateResult":
        objected_template = cls(template)
        return objected_template.format(data)

    @classmethod
    def format_strict_template(
        cls, template: str, data: dict[str, Any]
    ) -> "TemplateResult":
        objected_template = cls(template)
        return objected_template.format_strict(data)

    @staticmethod
    def find_optional_parts(
        parts: list[Union[str, FormattingPart]]
    ) -> list[Union[str, OptionalPart, FormattingPart]]:
        new_parts = []
        tmp_parts = {}
        counted_symb = -1
        for part in parts:
            if part == "<":
                counted_symb += 1
                tmp_parts[counted_symb] = []

            elif part == ">":
                if counted_symb > -1:
                    parts = tmp_parts.pop(counted_symb)
                    counted_symb -= 1
                    # If part contains only single string keep value
                    #   unchanged
                    if parts:
                        # Remove optional start char
                        parts.pop(0)

                    if not parts:
                        value = "<>"
                    elif (
                        len(parts) == 1
                        and isinstance(parts[0], str)
                    ):
                        value = f"<{parts[0]}>"
                    else:
                        value = OptionalPart(parts)

                    if counted_symb < 0:
                        out_parts = new_parts
                    else:
                        out_parts = tmp_parts[counted_symb]
                    # Store value
                    out_parts.append(value)
                    continue

            if counted_symb < 0:
                new_parts.append(part)
            else:
                tmp_parts[counted_symb].append(part)

        if tmp_parts:
            for idx in sorted(tmp_parts.keys()):
                new_parts.extend(tmp_parts[idx])
        return new_parts

format(data)

Figure out with whole formatting.

Separate advanced keys (*Like '{project[name]}') from string which must be formatted separately in case of missing or incomplete keys in data.

Parameters:

Name Type Description Default
data dict

Containing keys to be filled into template.

required

Returns:

Name Type Description
TemplateResult 'TemplateResult'

Filled or partially filled template containing all data needed or missing for filling template.

Source code in client/ayon_core/lib/path_templates.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def format(self, data: dict[str, Any]) -> "TemplateResult":
    """ Figure out with whole formatting.

    Separate advanced keys (*Like '{project[name]}') from string which must
    be formatted separately in case of missing or incomplete keys in data.

    Args:
        data (dict): Containing keys to be filled into template.

    Returns:
        TemplateResult: Filled or partially filled template containing all
            data needed or missing for filling template.

    """
    result = TemplatePartResult()
    for part in self._parts:
        if isinstance(part, str):
            result.add_output(part)
        else:
            part.format(data, result)

    invalid_types = result.invalid_types
    invalid_types.update(result.invalid_optional_types)
    invalid_types = result.split_keys_to_subdicts(invalid_types)

    missing_keys = result.missing_keys
    missing_keys |= result.missing_optional_keys

    solved = result.solved
    used_values = result.get_clean_used_values()

    return TemplateResult(
        result.output,
        self.template,
        solved,
        used_values,
        missing_keys,
        invalid_types
    )

remove_optional_parts_for_data(data=None)

Remove optional parts from template for data.

This method does not modify the template object itself.

Note

At this moment the functionality is not 1:1 with 'format' where lists are supported and the values are validated.

Parameters:

Name Type Description Default
data Optional[dict[str, Any]]

Template data for template.

None

Returns:

Name Type Description
str str

Template without optional parts that are not available in passed data.

Source code in client/ayon_core/lib/path_templates.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def remove_optional_parts_for_data(
    self,
    data: Optional[dict[str, Any]] = None,
) -> str:
    """Remove optional parts from template for data.

    This method does not modify the template object itself.

    Note:
        At this moment the functionality is not 1:1 with 'format' where
            lists are supported and the values are validated.

    Args:
        data (Optional[dict[str, Any]]): Template data for template.

    Returns:
        str: Template without optional parts that are not available
            in passed data.

    """
    if data is None:
        data = {}

    output = ""
    for part in self._parts:
        if isinstance(part, str):
            output += part
        elif isinstance(part, FormattingPart):
            output += part.template
        elif isinstance(part, OptionalPart):
            output += part.remove_optional_parts_for_data(data)
        else:
            raise TypeError(
                f"Got invalid type in template parts '{type(part)}'"
            )
    return output

TemplatePartResult

Result to store result of template parts.

Source code in client/ayon_core/lib/path_templates.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
class TemplatePartResult:
    """Result to store result of template parts."""
    def __init__(self, optional: bool = False):
        # Missing keys or invalid value types of required keys
        self._missing_keys: set[str] = set()
        self._invalid_types: dict[str, Any] = {}
        # Missing keys or invalid value types of optional keys
        self._missing_optional_keys: set[str] = set()
        self._invalid_optional_types: dict[str, Any] = {}

        # Used values stored by key with origin type
        #   - key without any padding or key modifiers
        #   - value from filling data
        #   Example: {"version": 1}
        self._used_values: dict[str, Any] = {}
        # Used values stored by key with all modifirs
        #   - value is already formatted string
        #   Example: {"version:0>3": "001"}
        self._really_used_values: dict[str, Any] = {}
        # Concatenated string output after formatting
        self._output: str = ""
        # Is this result from optional part
        # TODO find out why we don't use 'optional' from args
        self._optional: bool = True

    def add_output(self, other):
        if isinstance(other, str):
            self._output += other

        elif isinstance(other, TemplatePartResult):
            self._output += other.output

            self._missing_keys |= other.missing_keys
            self._missing_optional_keys |= other.missing_optional_keys

            self._invalid_types.update(other.invalid_types)
            self._invalid_optional_types.update(other.invalid_optional_types)

            if other.optional and not other.solved:
                return
            self._used_values.update(other.used_values)
            self._really_used_values.update(other.really_used_values)

        else:
            raise TypeError(
                f"Cannot add data from \"{type(other)}\""
                f" to \"{self.__class__.__name__}\""
            )

    @property
    def solved(self) -> bool:
        if self.optional:
            if (
                len(self.missing_optional_keys) > 0
                or len(self.invalid_optional_types) > 0
            ):
                return False
        return (
            len(self.missing_keys) == 0
            and len(self.invalid_types) == 0
        )

    @property
    def optional(self) -> bool:
        return self._optional

    @property
    def output(self) -> str:
        return self._output

    @property
    def missing_keys(self) -> set[str]:
        return self._missing_keys

    @property
    def missing_optional_keys(self) -> set[str]:
        return self._missing_optional_keys

    @property
    def invalid_types(self) -> dict[str, Any]:
        return self._invalid_types

    @property
    def invalid_optional_types(self) -> dict[str, Any]:
        return self._invalid_optional_types

    @property
    def really_used_values(self) -> dict[str, Any]:
        return self._really_used_values

    @property
    def realy_used_values(self) -> dict[str, Any]:
        warnings.warn(
            "Property 'realy_used_values' is deprecated."
            " Use 'really_used_values' instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        return self._really_used_values

    @property
    def used_values(self) -> dict[str, Any]:
        return self._used_values

    @staticmethod
    def split_keys_to_subdicts(values: dict[str, Any]) -> dict[str, Any]:
        output = {}
        formatter = Formatter()
        for key, value in values.items():
            _, field_name, _, _ = next(formatter.parse(f"{{{key}}}"))
            key_subdict = list(SUB_DICT_PATTERN.findall(field_name))
            data = output
            last_key = key_subdict.pop(-1)
            for subkey in key_subdict:
                if subkey not in data:
                    data[subkey] = {}
                data = data[subkey]
            data[last_key] = value
        return output

    def get_clean_used_values(self) -> dict[str, Any]:
        new_used_values = {}
        for key, value in self.used_values.items():
            if isinstance(value, FormatObject):
                value = str(value)
            new_used_values[key] = value

        return self.split_keys_to_subdicts(new_used_values)

    def add_really_used_value(self, key: str, value: Any):
        self._really_used_values[key] = value

    def add_realy_used_value(self, key: str, value: Any):
        warnings.warn(
            "Method 'add_realy_used_value' is deprecated."
            " Use 'add_really_used_value' instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        self.add_really_used_value(key, value)

    def add_used_value(self, key: str, value: Any):
        self._used_values[key] = value

    def add_missing_key(self, key: str):
        if self._optional:
            self._missing_optional_keys.add(key)
        else:
            self._missing_keys.add(key)

    def add_invalid_type(self, key: str, value: Any):
        if self._optional:
            self._invalid_optional_types[key] = type(value)
        else:
            self._invalid_types[key] = type(value)

TemplateResult

Bases: str

Result of template format with most of the information in.

Parameters:

Name Type Description Default
used_values dict

Dictionary of template filling data with only used keys.

required
solved bool

For check if all required keys were filled.

required
template str

Original template.

required
missing_keys list[str]

Missing keys that were not in the data. Include missing optional keys.

required
invalid_types dict

When key was found in data, but value had not allowed DataType. Allowed data types are numbers, str(basestring) and dict. Dictionary may cause invalid type when value of key in data is dictionary but template expect string of number.

required
Source code in client/ayon_core/lib/path_templates.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
class TemplateResult(str):
    """Result of template format with most of the information in.

    Args:
        used_values (dict): Dictionary of template filling data with
            only used keys.
        solved (bool): For check if all required keys were filled.
        template (str): Original template.
        missing_keys (list[str]): Missing keys that were not in the data.
            Include missing optional keys.
        invalid_types (dict): When key was found in data, but value had not
            allowed DataType. Allowed data types are `numbers`,
            `str`(`basestring`) and `dict`. Dictionary may cause invalid type
            when value of key in data is dictionary but template expect string
            of number.
    """

    used_values: dict[str, Any] = None
    solved: bool = None
    template: str = None
    missing_keys: list[str] = None
    invalid_types: dict[str, Any] = None

    def __new__(
        cls, filled_template, template, solved,
        used_values, missing_keys, invalid_types
    ):
        new_obj = super(TemplateResult, cls).__new__(cls, filled_template)
        new_obj.used_values = used_values
        new_obj.solved = solved
        new_obj.template = template
        new_obj.missing_keys = list(set(missing_keys))
        new_obj.invalid_types = invalid_types
        return new_obj

    def __copy__(self, *args, **kwargs):
        return self.copy()

    def __deepcopy__(self, *args, **kwargs):
        return self.copy()

    def validate(self):
        if not self.solved:
            raise TemplateUnsolved(
                self.template,
                self.missing_keys,
                self.invalid_types
            )

    def copy(self) -> "TemplateResult":
        cls = self.__class__
        return cls(
            str(self),
            self.template,
            self.solved,
            self.used_values,
            self.missing_keys,
            self.invalid_types
        )

    def normalized(self) -> "TemplateResult":
        """Convert to normalized path."""

        cls = self.__class__
        path = str(self)
        if _IS_WINDOWS:
            path = path.replace("\\", "/")
        return cls(
            os.path.normpath(path),
            self.template,
            self.solved,
            self.used_values,
            self.missing_keys,
            self.invalid_types
        )

normalized()

Convert to normalized path.

Source code in client/ayon_core/lib/path_templates.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def normalized(self) -> "TemplateResult":
    """Convert to normalized path."""

    cls = self.__class__
    path = str(self)
    if _IS_WINDOWS:
        path = path.replace("\\", "/")
    return cls(
        os.path.normpath(path),
        self.template,
        self.solved,
        self.used_values,
        self.missing_keys,
        self.invalid_types
    )

TemplateUnsolved

Bases: Exception

Exception for unsolved template when strict is set to True.

Source code in client/ayon_core/lib/path_templates.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class TemplateUnsolved(Exception):
    """Exception for unsolved template when strict is set to True."""

    msg = "Template \"{0}\" is unsolved.{1}{2}"
    invalid_types_msg = " Keys with invalid data type: `{0}`."
    missing_keys_msg = " Missing keys: \"{0}\"."

    def __init__(self, template, missing_keys, invalid_types):
        invalid_type_items = []
        for _key, _type in invalid_types.items():
            invalid_type_items.append(f"\"{_key}\" {str(_type)}")

        invalid_types_msg = ""
        if invalid_type_items:
            invalid_types_msg = self.invalid_types_msg.format(
                ", ".join(invalid_type_items)
            )

        missing_keys_msg = ""
        if missing_keys:
            missing_keys_msg = self.missing_keys_msg.format(
                ", ".join(missing_keys)
            )
        super().__init__(
            self.msg.format(template, missing_keys_msg, invalid_types_msg)
        )