Skip to content

attribute_definitions

AbstractAttrDef

Abstraction of attribute definition.

Each attribute definition must have implemented validation and conversion method.

Attribute definition should have ability to return "default" value. That can be based on passed data into __init__ so is not abstracted to attribute.

QUESTION: How to force to set key attribute?

Parameters:

Name Type Description Default
key str

Under which key will be attribute value stored.

required
default Any

Default value of an attribute.

required
label Optional[str]

Attribute label.

None
tooltip Optional[str]

Attribute tooltip.

None
is_label_horizontal Optional[bool]

UI specific argument. Specify if label is next to value input or ahead.

None
visible Optional[bool]

Item is shown to user (for UI purposes).

None
enabled Optional[bool]

Item is enabled (for UI purposes).

None
hidden Optional[bool]

DEPRECATED: Use 'visible' instead.

None
disabled Optional[bool]

DEPRECATED: Use 'enabled' instead.

None
Source code in client/ayon_core/lib/attribute_definitions.py
 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
class AbstractAttrDef(metaclass=AbstractAttrDefMeta):
    """Abstraction of attribute definition.

    Each attribute definition must have implemented validation and
    conversion method.

    Attribute definition should have ability to return "default" value. That
    can be based on passed data into `__init__` so is not abstracted to
    attribute.

    QUESTION:
    How to force to set `key` attribute?

    Args:
        key (str): Under which key will be attribute value stored.
        default (Any): Default value of an attribute.
        label (Optional[str]): Attribute label.
        tooltip (Optional[str]): Attribute tooltip.
        is_label_horizontal (Optional[bool]): UI specific argument. Specify
            if label is next to value input or ahead.
        visible (Optional[bool]): Item is shown to user (for UI purposes).
        enabled (Optional[bool]): Item is enabled (for UI purposes).
        hidden (Optional[bool]): DEPRECATED: Use 'visible' instead.
        disabled (Optional[bool]): DEPRECATED: Use 'enabled' instead.

    """
    type_attributes = []

    is_value_def = True

    def __init__(
        self,
        key: str,
        default: Any,
        label: Optional[str] = None,
        tooltip: Optional[str] = None,
        is_label_horizontal: Optional[bool] = None,
        visible: Optional[bool] = None,
        enabled: Optional[bool] = None,
        hidden: Optional[bool] = None,
        disabled: Optional[bool] = None,
    ):
        if is_label_horizontal is None:
            is_label_horizontal = True

        enabled = _convert_reversed_attr(
            enabled, disabled, "enabled", "disabled", True
        )
        visible = _convert_reversed_attr(
            visible, hidden, "visible", "hidden", True
        )

        self.key: str = key
        self.label: Optional[str] = label
        self.tooltip: Optional[str] = tooltip
        self.default: Any = default
        self.is_label_horizontal: bool = is_label_horizontal
        self.visible: bool = visible
        self.enabled: bool = enabled
        self._id: str = uuid.uuid4().hex

        self.__init__class__ = AbstractAttrDef

    @property
    def id(self) -> str:
        return self._id

    def clone(self) -> "Self":
        data = self.serialize()
        data.pop("type")
        return self.deserialize(data)

    @property
    def hidden(self) -> bool:
        return not self.visible

    @hidden.setter
    def hidden(self, value: bool):
        self.visible = not value

    @property
    def disabled(self) -> bool:
        return not self.enabled

    @disabled.setter
    def disabled(self, value: bool):
        self.enabled = not value

    def __eq__(self, other: Any) -> bool:
        return self.compare_to_def(other)

    def __ne__(self, other: Any) -> bool:
        return not self.compare_to_def(other)

    def compare_to_def(
        self,
        other: Any,
        ignore_default: Optional[bool] = False,
        ignore_enabled: Optional[bool] = False,
        ignore_visible: Optional[bool] = False,
        ignore_def_type_compare: Optional[bool] = False,
    ) -> bool:
        if not isinstance(other, self.__class__) or self.key != other.key:
            return False
        if not ignore_def_type_compare and not self._def_type_compare(other):
            return False
        return (
            (ignore_default or self.default == other.default)
            and (ignore_visible or self.visible == other.visible)
            and (ignore_enabled or self.enabled == other.enabled)
        )

    @abstractmethod
    def is_value_valid(self, value: Any) -> bool:
        """Check if value is valid.

        This should return False if value is not valid based
            on definition type.

        Args:
            value (Any): Value to validate based on definition type.

        Returns:
            bool: True if value is valid.

        """
        pass

    @property
    @abstractmethod
    def type(self) -> str:
        """Attribute definition type also used as identifier of class.

        Returns:
            str: Type of attribute definition.

        """
        pass

    @abstractmethod
    def convert_value(self, value: Any) -> Any:
        """Convert value to a valid one.

        Convert passed value to a valid type. Use default if value can't be
        converted.

        """
        pass

    def serialize(self) -> Dict[str, Any]:
        """Serialize object to data so it's possible to recreate it.

        Returns:
            Dict[str, Any]: Serialized object that can be passed to
                'deserialize' method.

        """
        data = {
            "type": self.type,
            "key": self.key,
            "label": self.label,
            "tooltip": self.tooltip,
            "default": self.default,
            "is_label_horizontal": self.is_label_horizontal,
            "visible": self.visible,
            "enabled": self.enabled
        }
        for attr in self.type_attributes:
            data[attr] = getattr(self, attr)
        return data

    @classmethod
    def deserialize(cls, data: Dict[str, Any]) -> "Self":
        """Recreate object from data.

        Data can be received using 'serialize' method.
        """
        if "type" in data:
            data = dict(data)
            data.pop("type")

        return cls(**data)

    def _def_type_compare(self, other: "Self") -> bool:
        return True

type abstractmethod property

Attribute definition type also used as identifier of class.

Returns:

Name Type Description
str str

Type of attribute definition.

convert_value(value) abstractmethod

Convert value to a valid one.

Convert passed value to a valid type. Use default if value can't be converted.

Source code in client/ayon_core/lib/attribute_definitions.py
238
239
240
241
242
243
244
245
246
@abstractmethod
def convert_value(self, value: Any) -> Any:
    """Convert value to a valid one.

    Convert passed value to a valid type. Use default if value can't be
    converted.

    """
    pass

deserialize(data) classmethod

Recreate object from data.

Data can be received using 'serialize' method.

Source code in client/ayon_core/lib/attribute_definitions.py
270
271
272
273
274
275
276
277
278
279
280
@classmethod
def deserialize(cls, data: Dict[str, Any]) -> "Self":
    """Recreate object from data.

    Data can be received using 'serialize' method.
    """
    if "type" in data:
        data = dict(data)
        data.pop("type")

    return cls(**data)

is_value_valid(value) abstractmethod

Check if value is valid.

This should return False if value is not valid based on definition type.

Parameters:

Name Type Description Default
value Any

Value to validate based on definition type.

required

Returns:

Name Type Description
bool bool

True if value is valid.

Source code in client/ayon_core/lib/attribute_definitions.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
@abstractmethod
def is_value_valid(self, value: Any) -> bool:
    """Check if value is valid.

    This should return False if value is not valid based
        on definition type.

    Args:
        value (Any): Value to validate based on definition type.

    Returns:
        bool: True if value is valid.

    """
    pass

serialize()

Serialize object to data so it's possible to recreate it.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Serialized object that can be passed to 'deserialize' method.

Source code in client/ayon_core/lib/attribute_definitions.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def serialize(self) -> Dict[str, Any]:
    """Serialize object to data so it's possible to recreate it.

    Returns:
        Dict[str, Any]: Serialized object that can be passed to
            'deserialize' method.

    """
    data = {
        "type": self.type,
        "key": self.key,
        "label": self.label,
        "tooltip": self.tooltip,
        "default": self.default,
        "is_label_horizontal": self.is_label_horizontal,
        "visible": self.visible,
        "enabled": self.enabled
    }
    for attr in self.type_attributes:
        data[attr] = getattr(self, attr)
    return data

AbstractAttrDefMeta

Bases: ABCMeta

Metaclass to validate the existence of 'key' attribute.

Each object of AbstractAttrDef must have defined 'key' attribute.

Source code in client/ayon_core/lib/attribute_definitions.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class AbstractAttrDefMeta(ABCMeta):
    """Metaclass to validate the existence of 'key' attribute.

    Each object of `AbstractAttrDef` must have defined 'key' attribute.

    """
    def __call__(cls, *args, **kwargs):
        obj = super(AbstractAttrDefMeta, cls).__call__(*args, **kwargs)
        init_class = getattr(obj, "__init__class__", None)
        if init_class is not AbstractAttrDef:
            raise TypeError("{} super was not called in __init__.".format(
                type(obj)
            ))
        return obj

BoolDef

Bases: AbstractAttrDef

Boolean representation.

Parameters:

Name Type Description Default
default(bool)

Default value. Set to False if not defined.

required
Source code in client/ayon_core/lib/attribute_definitions.py
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
class BoolDef(AbstractAttrDef):
    """Boolean representation.

    Args:
        default(bool): Default value. Set to `False` if not defined.

    """
    type = "bool"

    def __init__(self, key: str, default: Optional[bool] = None, **kwargs):
        if default is None:
            default = False
        super().__init__(key, default=default, **kwargs)

    def is_value_valid(self, value: Any) -> bool:
        return isinstance(value, bool)

    def convert_value(self, value: Any) -> bool:
        if isinstance(value, bool):
            return value
        return self.default

EnumDef

Bases: AbstractAttrDef

Enumeration of items.

Enumeration of single item from items. Or list of items if multiselection is enabled.

Parameters:

Name Type Description Default
key str

Key under which value is stored.

required
items EnumItemsInputType

Items definition that can be converted using 'prepare_enum_items'.

required
default Optional[Any]

Default value. Must be one key(value) from passed items or list of values for multiselection.

None
multiselection Optional[bool]

If True, multiselection is allowed. Output is list of selected items.

False
placeholder Optional[str]

Placeholder for UI purposes, only for multiselection enumeration.

None
Source code in client/ayon_core/lib/attribute_definitions.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
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
class EnumDef(AbstractAttrDef):
    """Enumeration of items.

    Enumeration of single item from items. Or list of items if multiselection
    is enabled.

    Args:
        key (str): Key under which value is stored.
        items (EnumItemsInputType): Items definition that can be converted
            using 'prepare_enum_items'.
        default (Optional[Any]): Default value. Must be one key(value) from
            passed items or list of values for multiselection.
        multiselection (Optional[bool]): If True, multiselection is allowed.
            Output is list of selected items.
        placeholder (Optional[str]): Placeholder for UI purposes, only for
            multiselection enumeration.

    """
    type = "enum"

    type_attributes = [
        "multiselection",
        "placeholder",
    ]

    def __init__(
        self,
        key: str,
        items: "EnumItemsInputType",
        default: "Union[str, List[Any]]" = None,
        multiselection: Optional[bool] = False,
        placeholder: Optional[str] = None,
        **kwargs
    ):
        if multiselection is None:
            multiselection = False

        if not items and not multiselection:
            raise ValueError(
                f"Empty 'items' value. {self.__class__.__name__} must have"
                " defined values on initialization."
            )

        items = self.prepare_enum_items(items)
        item_values = [item["value"] for item in items]
        item_values_set = set(item_values)

        if multiselection:
            if default is None:
                default = []
            default = list(item_values_set.intersection(default))

        elif default not in item_values:
            default = next(iter(item_values), None)

        super().__init__(key, default=default, **kwargs)

        self.items: List["EnumItemDict"] = items
        self._item_values: Set[Any] = item_values_set
        self.multiselection: bool = multiselection
        self.placeholder: Optional[str] = placeholder

    def convert_value(self, value):
        if not self.multiselection:
            if value in self._item_values:
                return value
            return self.default

        if value is None:
            return copy.deepcopy(self.default)
        return list(self._item_values.intersection(value))

    def is_value_valid(self, value: Any) -> bool:
        """Check if item is available in possible values."""
        if isinstance(value, list):
            if not self.multiselection:
                return False
            return all(value in self._item_values for value in value)

        if self.multiselection:
            return False
        return value in self._item_values

    def serialize(self):
        data = super().serialize()
        data["items"] = copy.deepcopy(self.items)
        return data

    @staticmethod
    def prepare_enum_items(
        items: "EnumItemsInputType"
    ) -> List["EnumItemDict"]:
        """Convert items to unified structure.

        Output is a list where each item is dictionary with 'value'
        and 'label'.

        ```python
        # Example output
        [
            {"label": "Option 1", "value": 1},
            {"label": "Option 2", "value": 2},
            {"label": "Option 3", "value": 3}
        ]
        ```

        Args:
            items (EnumItemsInputType): The items to convert.

        Returns:
            List[EnumItemDict]: Unified structure of items.

        """
        output = []
        if isinstance(items, dict):
            for value, label in items.items():
                output.append({"label": label, "value": value})

        elif isinstance(items, (tuple, list, set)):
            for item in items:
                if isinstance(item, dict):
                    # Validate if 'value' is available
                    if "value" not in item:
                        raise KeyError("Item does not contain 'value' key.")

                    if "label" not in item:
                        item["label"] = str(item["value"])
                elif isinstance(item, (list, tuple)):
                    if len(item) == 2:
                        value, label = item
                    elif len(item) == 1:
                        value = item[0]
                        label = str(value)
                    else:
                        raise ValueError((
                            "Invalid items count {}."
                            " Expected 1 or 2. Value: {}"
                        ).format(len(item), str(item)))

                    item = {"label": label, "value": value}
                else:
                    item = {"label": str(item), "value": item}
                output.append(item)

        else:
            raise TypeError(
                "Unknown type for enum items '{}'".format(type(items))
            )

        return output

    def _def_type_compare(self, other: "EnumDef") -> bool:
        return (
            self.items == other.items
            and self.multiselection == other.multiselection
        )

is_value_valid(value)

Check if item is available in possible values.

Source code in client/ayon_core/lib/attribute_definitions.py
611
612
613
614
615
616
617
618
619
620
def is_value_valid(self, value: Any) -> bool:
    """Check if item is available in possible values."""
    if isinstance(value, list):
        if not self.multiselection:
            return False
        return all(value in self._item_values for value in value)

    if self.multiselection:
        return False
    return value in self._item_values

prepare_enum_items(items) staticmethod

Convert items to unified structure.

Output is a list where each item is dictionary with 'value' and 'label'.

# Example output
[
    {"label": "Option 1", "value": 1},
    {"label": "Option 2", "value": 2},
    {"label": "Option 3", "value": 3}
]

Parameters:

Name Type Description Default
items EnumItemsInputType

The items to convert.

required

Returns:

Type Description
List[EnumItemDict]

List[EnumItemDict]: Unified structure of items.

Source code in client/ayon_core/lib/attribute_definitions.py
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
@staticmethod
def prepare_enum_items(
    items: "EnumItemsInputType"
) -> List["EnumItemDict"]:
    """Convert items to unified structure.

    Output is a list where each item is dictionary with 'value'
    and 'label'.

    ```python
    # Example output
    [
        {"label": "Option 1", "value": 1},
        {"label": "Option 2", "value": 2},
        {"label": "Option 3", "value": 3}
    ]
    ```

    Args:
        items (EnumItemsInputType): The items to convert.

    Returns:
        List[EnumItemDict]: Unified structure of items.

    """
    output = []
    if isinstance(items, dict):
        for value, label in items.items():
            output.append({"label": label, "value": value})

    elif isinstance(items, (tuple, list, set)):
        for item in items:
            if isinstance(item, dict):
                # Validate if 'value' is available
                if "value" not in item:
                    raise KeyError("Item does not contain 'value' key.")

                if "label" not in item:
                    item["label"] = str(item["value"])
            elif isinstance(item, (list, tuple)):
                if len(item) == 2:
                    value, label = item
                elif len(item) == 1:
                    value = item[0]
                    label = str(value)
                else:
                    raise ValueError((
                        "Invalid items count {}."
                        " Expected 1 or 2. Value: {}"
                    ).format(len(item), str(item)))

                item = {"label": label, "value": value}
            else:
                item = {"label": str(item), "value": item}
            output.append(item)

    else:
        raise TypeError(
            "Unknown type for enum items '{}'".format(type(items))
        )

    return output

FileDef

Bases: AbstractAttrDef

File definition. It is possible to define filters of allowed file extensions and if supports folders. Args: single_item(bool): Allow only single path item. folders(bool): Allow folder paths. extensions(List[str]): Allow files with extensions. Empty list will allow all extensions and None will disable files completely. extensions_label(str): Custom label shown instead of extensions in UI. default(str, List[str]): Default value.

Source code in client/ayon_core/lib/attribute_definitions.py
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
class FileDef(AbstractAttrDef):
    """File definition.
    It is possible to define filters of allowed file extensions and if supports
    folders.
    Args:
        single_item(bool): Allow only single path item.
        folders(bool): Allow folder paths.
        extensions(List[str]): Allow files with extensions. Empty list will
            allow all extensions and None will disable files completely.
        extensions_label(str): Custom label shown instead of extensions in UI.
        default(str, List[str]): Default value.
    """

    type = "path"
    type_attributes = [
        "single_item",
        "folders",
        "extensions",
        "allow_sequences",
        "extensions_label",
    ]

    def __init__(
        self,
        key: str,
        single_item: Optional[bool] = True,
        folders: Optional[bool] = None,
        extensions: Optional[Iterable[str]] = None,
        allow_sequences: Optional[bool] = True,
        extensions_label: Optional[str] = None,
        default: Optional["Union[FileDefItemDict, List[str]]"] = None,
        **kwargs
    ):
        if folders is None and extensions is None:
            folders = True
            extensions = []

        if default is None:
            if single_item:
                default = FileDefItem.create_empty_item().to_dict()
            else:
                default = []
        else:
            if single_item:
                if isinstance(default, dict):
                    FileDefItem.from_dict(default)

                elif isinstance(default, str):
                    default = FileDefItem.from_paths(
                        [default.strip()], allow_sequences
                    )[0]

                else:
                    raise TypeError((
                        "'default' argument must be 'str' or 'dict' not '{}'"
                    ).format(type(default)))

            else:
                if not isinstance(default, (tuple, list, set)):
                    raise TypeError((
                        "'default' argument must be 'list', 'tuple' or 'set'"
                        ", not '{}'"
                    ).format(type(default)))

        # Change horizontal label
        is_label_horizontal = kwargs.get("is_label_horizontal")
        if is_label_horizontal is None:
            kwargs["is_label_horizontal"] = False

        self.single_item: bool = single_item
        self.folders: bool = folders
        self.extensions: Set[str] = set(extensions)
        self.allow_sequences: bool = allow_sequences
        self.extensions_label: Optional[str] = extensions_label
        super().__init__(key, default=default, **kwargs)

    def __eq__(self, other: Any) -> bool:
        if not super().__eq__(other):
            return False

        return (
            self.single_item == other.single_item
            and self.folders == other.folders
            and self.extensions == other.extensions
            and self.allow_sequences == other.allow_sequences
        )

    def is_value_valid(self, value: Any) -> bool:
        if self.single_item:
            if not isinstance(value, dict):
                return False
            try:
                FileDefItem.from_dict(value)
                return True
            except (ValueError, KeyError):
                return False

        if not isinstance(value, list):
            return False

        for item in value:
            if not isinstance(item, dict):
                return False

            try:
                FileDefItem.from_dict(item)
            except (ValueError, KeyError):
                return False
        return True

    def convert_value(
        self, value: Any
    ) -> "Union[FileDefItemDict, List[FileDefItemDict]]":
        if isinstance(value, (str, dict)):
            value = [value]

        if isinstance(value, (tuple, list, set)):
            string_paths = []
            dict_items = []
            for item in value:
                if isinstance(item, str):
                    string_paths.append(item.strip())
                elif isinstance(item, dict):
                    try:
                        FileDefItem.from_dict(item)
                        dict_items.append(item)
                    except (ValueError, KeyError):
                        pass

            if string_paths:
                file_items = FileDefItem.from_paths(
                    string_paths, self.allow_sequences
                )
                dict_items.extend([
                    file_item.to_dict()
                    for file_item in file_items
                ])

            if not self.single_item:
                return dict_items

            if not dict_items:
                return self.default
            return dict_items[0]

        if self.single_item:
            return FileDefItem.create_empty_item().to_dict()
        return []

FileDefItem

Source code in client/ayon_core/lib/attribute_definitions.py
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
777
778
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
class FileDefItem:
    def __init__(
        self,
        directory: str,
        filenames: List[str],
        frames: Optional[List[int]] = None,
        template: Optional[str] = None,
    ):
        self.directory = directory

        self.filenames = []
        self.is_sequence = False
        self.template = None
        self.frames = []
        self.is_empty = True

        self.set_filenames(filenames, frames, template)

    def __str__(self):
        return json.dumps(self.to_dict())

    def __repr__(self):
        if self.is_empty:
            filename = "< empty >"
        elif self.is_sequence:
            filename = self.template
        else:
            filename = self.filenames[0]

        return "<{}: \"{}\">".format(
            self.__class__.__name__,
            os.path.join(self.directory, filename)
        )

    @property
    def label(self) -> Optional[str]:
        if self.is_empty:
            return None

        if not self.is_sequence:
            return self.filenames[0]

        frame_start = self.frames[0]
        filename_template = os.path.basename(self.template)
        if len(self.frames) == 1:
            return "{} [{}]".format(filename_template, frame_start)

        frame_end = self.frames[-1]
        expected_len = (frame_end - frame_start) + 1
        if expected_len == len(self.frames):
            return "{} [{}-{}]".format(
                filename_template, frame_start, frame_end
            )

        ranges = []
        _frame_start = None
        _frame_end = None
        for frame in range(frame_start, frame_end + 1):
            if frame not in self.frames:
                add_to_ranges = _frame_start is not None
            elif _frame_start is None:
                _frame_start = _frame_end = frame
                add_to_ranges = frame == frame_end
            else:
                _frame_end = frame
                add_to_ranges = frame == frame_end

            if add_to_ranges:
                if _frame_start != _frame_end:
                    _range = "{}-{}".format(_frame_start, _frame_end)
                else:
                    _range = str(_frame_start)
                ranges.append(_range)
                _frame_start = _frame_end = None
        return "{} [{}]".format(
            filename_template, ",".join(ranges)
        )

    def split_sequence(self) -> List["Self"]:
        if not self.is_sequence:
            raise ValueError("Cannot split single file item")

        paths = [
            os.path.join(self.directory, filename)
            for filename in self.filenames
        ]
        return self.from_paths(paths, False)

    @property
    def ext(self) -> Optional[str]:
        if self.is_empty:
            return None
        _, ext = os.path.splitext(self.filenames[0])
        if ext:
            return ext
        return None

    @property
    def lower_ext(self) -> Optional[str]:
        ext = self.ext
        if ext is not None:
            return ext.lower()
        return ext

    @property
    def is_dir(self) -> bool:
        if self.is_empty:
            return False

        # QUESTION a better way how to define folder (in init argument?)
        if self.ext:
            return False
        return True

    def set_directory(self, directory: str):
        self.directory = directory

    def set_filenames(
        self,
        filenames: List[str],
        frames: Optional[List[int]] = None,
        template: Optional[str] = None,
    ):
        if frames is None:
            frames = []
        is_sequence = False
        if frames:
            is_sequence = True

        if is_sequence and not template:
            raise ValueError("Missing template for sequence")

        self.is_empty = len(filenames) == 0
        self.filenames = filenames
        self.template = template
        self.frames = frames
        self.is_sequence = is_sequence

    @classmethod
    def create_empty_item(cls) -> "Self":
        return cls("", "")

    @classmethod
    def from_value(
        cls,
        value: "Union[List[FileDefItemDict], FileDefItemDict]",
        allow_sequences: bool,
    ) -> List["Self"]:
        """Convert passed value to FileDefItem objects.

        Returns:
            list: Created FileDefItem objects.

        """
        # Convert single item to iterable
        if not isinstance(value, (list, tuple, set)):
            value = [value]

        output = []
        str_filepaths = []
        for item in value:
            if isinstance(item, dict):
                item = cls.from_dict(item)

            if isinstance(item, FileDefItem):
                if not allow_sequences and item.is_sequence:
                    output.extend(item.split_sequence())
                else:
                    output.append(item)

            elif isinstance(item, str):
                str_filepaths.append(item)
            else:
                raise TypeError(
                    "Unknown type \"{}\". Can't convert to {}".format(
                        str(type(item)), cls.__name__
                    )
                )

        if str_filepaths:
            output.extend(cls.from_paths(str_filepaths, allow_sequences))

        return output

    @classmethod
    def from_dict(cls, data: "FileDefItemDict") -> "Self":
        return cls(
            data["directory"],
            data["filenames"],
            data.get("frames"),
            data.get("template")
        )

    @classmethod
    def from_paths(
        cls,
        paths: List[str],
        allow_sequences: bool,
    ) -> List["Self"]:
        filenames_by_dir = collections.defaultdict(list)
        for path in paths:
            normalized = os.path.normpath(path)
            directory, filename = os.path.split(normalized)
            filenames_by_dir[directory].append(filename)

        output = []
        for directory, filenames in filenames_by_dir.items():
            if allow_sequences:
                cols, remainders = clique.assemble(filenames)
            else:
                cols = []
                remainders = filenames

            for remainder in remainders:
                output.append(cls(directory, [remainder]))

            for col in cols:
                frames = list(col.indexes)
                paths = [filename for filename in col]
                template = col.format("{head}{padding}{tail}")

                output.append(cls(
                    directory, paths, frames, template
                ))

        return output

    def to_dict(self) -> "FileDefItemDict":
        output = {
            "is_sequence": self.is_sequence,
            "directory": self.directory,
            "filenames": list(self.filenames),
        }
        if self.is_sequence:
            output.update({
                "template": self.template,
                "frames": list(sorted(self.frames)),
            })

        return output

from_value(value, allow_sequences) classmethod

Convert passed value to FileDefItem objects.

Returns:

Name Type Description
list List[Self]

Created FileDefItem objects.

Source code in client/ayon_core/lib/attribute_definitions.py
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
@classmethod
def from_value(
    cls,
    value: "Union[List[FileDefItemDict], FileDefItemDict]",
    allow_sequences: bool,
) -> List["Self"]:
    """Convert passed value to FileDefItem objects.

    Returns:
        list: Created FileDefItem objects.

    """
    # Convert single item to iterable
    if not isinstance(value, (list, tuple, set)):
        value = [value]

    output = []
    str_filepaths = []
    for item in value:
        if isinstance(item, dict):
            item = cls.from_dict(item)

        if isinstance(item, FileDefItem):
            if not allow_sequences and item.is_sequence:
                output.extend(item.split_sequence())
            else:
                output.append(item)

        elif isinstance(item, str):
            str_filepaths.append(item)
        else:
            raise TypeError(
                "Unknown type \"{}\". Can't convert to {}".format(
                    str(type(item)), cls.__name__
                )
            )

    if str_filepaths:
        output.extend(cls.from_paths(str_filepaths, allow_sequences))

    return output

HiddenDef

Bases: AbstractAttrDef

Hidden value of Any type.

This attribute can be used for UI purposes to pass values related to other attributes (e.g. in multi-page UIs).

Keep in mind the value should be possible to parse by json parser.

Source code in client/ayon_core/lib/attribute_definitions.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class HiddenDef(AbstractAttrDef):
    """Hidden value of Any type.

    This attribute can be used for UI purposes to pass values related
    to other attributes (e.g. in multi-page UIs).

    Keep in mind the value should be possible to parse by json parser.

    """
    type = "hidden"

    def __init__(self, key: str, default: Optional[Any] = None, **kwargs):
        kwargs["default"] = default
        kwargs["visible"] = False
        super().__init__(key, **kwargs)

    def is_value_valid(self, value: Any) -> bool:
        return True

    def convert_value(self, value: Any) -> Any:
        return value

NumberDef

Bases: AbstractAttrDef

Number definition.

Number can have defined minimum/maximum value and decimal points. Value is integer if decimals are 0.

Parameters:

Name Type Description Default
minimum(int, float

Minimum possible value.

required
maximum(int, float

Maximum possible value.

required
decimals(int)

Maximum decimal points of value.

required
default(int, float

Default value for conversion.

required
Source code in client/ayon_core/lib/attribute_definitions.py
372
373
374
375
376
377
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
class NumberDef(AbstractAttrDef):
    """Number definition.

    Number can have defined minimum/maximum value and decimal points. Value
    is integer if decimals are 0.

    Args:
        minimum(int, float): Minimum possible value.
        maximum(int, float): Maximum possible value.
        decimals(int): Maximum decimal points of value.
        default(int, float): Default value for conversion.

    """
    type = "number"
    type_attributes = [
        "minimum",
        "maximum",
        "decimals"
    ]

    def __init__(
        self,
        key: str,
        minimum: Optional[IntFloatType] = None,
        maximum: Optional[IntFloatType] = None,
        decimals: Optional[int] = None,
        default: Optional[IntFloatType] = None,
        **kwargs
    ):
        minimum = 0 if minimum is None else minimum
        maximum = 999999 if maximum is None else maximum
        # Swap min/max when are passed in opposite order
        if minimum > maximum:
            maximum, minimum = minimum, maximum

        if default is None:
            default = 0

        elif not isinstance(default, (int, float)):
            raise TypeError((
                "'default' argument must be 'int' or 'float', not '{}'"
            ).format(type(default)))

        # Fix default value by mim/max values
        if default < minimum:
            default = minimum

        elif default > maximum:
            default = maximum

        super().__init__(key, default=default, **kwargs)

        self.minimum: IntFloatType = minimum
        self.maximum: IntFloatType = maximum
        self.decimals: int = 0 if decimals is None else decimals

    def is_value_valid(self, value: Any) -> bool:
        if self.decimals == 0:
            if not isinstance(value, int):
                return False
        elif not isinstance(value, float):
            return False
        if self.minimum > value > self.maximum:
            return False
        return True

    def convert_value(self, value: Any) -> IntFloatType:
        if isinstance(value, str):
            try:
                value = float(value)
            except Exception:
                pass

        if not isinstance(value, (int, float)):
            return self.default

        if self.decimals == 0:
            return int(value)
        return round(float(value), self.decimals)

    def _def_type_compare(self, other: "NumberDef") -> bool:
        return (
            self.decimals == other.decimals
            and self.maximum == other.maximum
            and self.maximum == other.maximum
        )

TextDef

Bases: AbstractAttrDef

Text definition.

Text can have multiline option so end-line characters are allowed regex validation can be applied placeholder for UI purposes and default value.

Regex validation is not part of attribute implementation.

Parameters:

Name Type Description Default
multiline(bool)

Text has single or multiline support.

required
regex(str, Pattern

Regex validation.

required
placeholder(str)

UI placeholder for attribute.

required
default(str, None

Default value. Empty string used when not defined.

required
Source code in client/ayon_core/lib/attribute_definitions.py
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
533
534
535
536
class TextDef(AbstractAttrDef):
    """Text definition.

    Text can have multiline option so end-line characters are allowed regex
    validation can be applied placeholder for UI purposes and default value.

    Regex validation is not part of attribute implementation.

    Args:
        multiline(bool): Text has single or multiline support.
        regex(str, re.Pattern): Regex validation.
        placeholder(str): UI placeholder for attribute.
        default(str, None): Default value. Empty string used when not defined.

    """
    type = "text"
    type_attributes = [
        "multiline",
        "placeholder",
    ]

    def __init__(
        self,
        key: str,
        multiline: Optional[bool] = None,
        regex: Optional[str] = None,
        placeholder: Optional[str] = None,
        default: Optional[str] = None,
        **kwargs
    ):
        if default is None:
            default = ""

        super().__init__(key, default=default, **kwargs)

        if multiline is None:
            multiline = False

        elif not isinstance(default, str):
            raise TypeError((
                f"'default' argument must be a str, not '{type(default)}'"
            ))

        if isinstance(regex, str):
            regex = re.compile(regex)

        self.multiline: bool = multiline
        self.placeholder: Optional[str] = placeholder
        self.regex: Optional["Pattern"] = regex

    def is_value_valid(self, value: Any) -> bool:
        if not isinstance(value, str):
            return False
        if self.regex and not self.regex.match(value):
            return False
        return True

    def convert_value(self, value: Any) -> str:
        if isinstance(value, str):
            return value
        return self.default

    def serialize(self) -> Dict[str, Any]:
        data = super().serialize()
        regex = None
        if self.regex is not None:
            regex = self.regex.pattern
        data["regex"] = regex
        data["multiline"] = self.multiline
        data["placeholder"] = self.placeholder
        return data

    def _def_type_compare(self, other: "TextDef") -> bool:
        return (
            self.multiline == other.multiline
            and self.regex == other.regex
        )

UnknownDef

Bases: AbstractAttrDef

Definition is not known because definition is not available.

This attribute can be used to keep existing data unchanged but does not have known definition of type.

Source code in client/ayon_core/lib/attribute_definitions.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
class UnknownDef(AbstractAttrDef):
    """Definition is not known because definition is not available.

    This attribute can be used to keep existing data unchanged but does not
    have known definition of type.

    """
    type = "unknown"

    def __init__(self, key: str, default: Optional[Any] = None, **kwargs):
        kwargs["default"] = default
        super().__init__(key, **kwargs)

    def is_value_valid(self, value: Any) -> bool:
        return True

    def convert_value(self, value: Any) -> Any:
        return value

deserialize_attr_def(attr_def_data)

Deserialize attribute definition from data.

Parameters:

Name Type Description Default
attr_def_data Dict[str, Any]

Attribute definition data to deserialize.

required
Source code in client/ayon_core/lib/attribute_definitions.py
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
def deserialize_attr_def(attr_def_data: Dict[str, Any]) -> AttrDefType:
    """Deserialize attribute definition from data.

    Args:
        attr_def_data (Dict[str, Any]): Attribute definition data to
            deserialize.

    """
    attr_type = attr_def_data.pop("type")
    cls = _attr_defs_by_type[attr_type]
    return cls.deserialize(attr_def_data)

deserialize_attr_defs(attr_defs_data)

Deserialize attribute definitions.

Parameters:

Name Type Description Default
List[Dict[str, Any]]

List of attribute definitions.

required
Source code in client/ayon_core/lib/attribute_definitions.py
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
def deserialize_attr_defs(
    attr_defs_data: List[Dict[str, Any]]
) -> List[AttrDefType]:
    """Deserialize attribute definitions.

    Args:
        List[Dict[str, Any]]: List of attribute definitions.

    """
    return [
        deserialize_attr_def(attr_def_data)
        for attr_def_data in attr_defs_data
    ]

get_attributes_keys(attribute_definitions)

Collect keys from list of attribute definitions.

Parameters:

Name Type Description Default
attribute_definitions List[AttrDefType]

Objects of attribute definitions.

required

Returns:

Type Description
Set[str]

Set[str]: Keys that will be created using passed attribute definitions.

Source code in client/ayon_core/lib/attribute_definitions.py
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
def get_attributes_keys(
    attribute_definitions: List[AttrDefType]
) -> Set[str]:
    """Collect keys from list of attribute definitions.

    Args:
        attribute_definitions (List[AttrDefType]): Objects of attribute
            definitions.

    Returns:
        Set[str]: Keys that will be created using passed attribute definitions.

    """
    keys = set()
    if not attribute_definitions:
        return keys

    for attribute_def in attribute_definitions:
        if not isinstance(attribute_def, UIDef):
            keys.add(attribute_def.key)
    return keys

get_default_values(attribute_definitions)

Receive default values for attribute definitions.

Parameters:

Name Type Description Default
attribute_definitions List[AttrDefType]

Attribute definitions for which default values should be collected.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Default values for passed attribute definitions.

Source code in client/ayon_core/lib/attribute_definitions.py
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
def get_default_values(
    attribute_definitions: List[AttrDefType]
) -> Dict[str, Any]:
    """Receive default values for attribute definitions.

    Args:
        attribute_definitions (List[AttrDefType]): Attribute definitions
            for which default values should be collected.

    Returns:
        Dict[str, Any]: Default values for passed attribute definitions.

    """
    output = {}
    if not attribute_definitions:
        return output

    for attr_def in attribute_definitions:
        # Skip UI definitions
        if not isinstance(attr_def, UIDef):
            output[attr_def.key] = attr_def.default
    return output

register_attr_def_class(cls)

Register attribute definition.

Currently registered definitions are used to deserialize data to objects.

Attrs

cls (AttrDefType): Non-abstract class to be registered with unique 'type' attribute.

Raises:

Type Description
KeyError

When type was already registered.

Source code in client/ayon_core/lib/attribute_definitions.py
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
def register_attr_def_class(cls: AttrDefType):
    """Register attribute definition.

    Currently registered definitions are used to deserialize data to objects.

    Attrs:
        cls (AttrDefType): Non-abstract class to be registered with unique
            'type' attribute.

    Raises:
        KeyError: When type was already registered.

    """
    if cls.type in _attr_defs_by_type:
        raise KeyError("Type \"{}\" was already registered".format(cls.type))
    _attr_defs_by_type[cls.type] = cls

serialize_attr_def(attr_def)

Serialize attribute definition to data.

Parameters:

Name Type Description Default
attr_def AttrDefType

Attribute definition to serialize.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Serialized data.

Source code in client/ayon_core/lib/attribute_definitions.py
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
def serialize_attr_def(attr_def: AttrDefType) -> Dict[str, Any]:
    """Serialize attribute definition to data.

    Args:
        attr_def (AttrDefType): Attribute definition to serialize.

    Returns:
        Dict[str, Any]: Serialized data.

    """
    return attr_def.serialize()

serialize_attr_defs(attr_defs)

Serialize attribute definitions to data.

Parameters:

Name Type Description Default
attr_defs List[AttrDefType]

Attribute definitions to serialize.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Serialized data.

Source code in client/ayon_core/lib/attribute_definitions.py
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
def serialize_attr_defs(
    attr_defs: List[AttrDefType]
) -> List[Dict[str, Any]]:
    """Serialize attribute definitions to data.

    Args:
        attr_defs (List[AttrDefType]): Attribute definitions to serialize.

    Returns:
        List[Dict[str, Any]]: Serialized data.

    """
    return [
        serialize_attr_def(attr_def)
        for attr_def in attr_defs
    ]