Exemplo n.º 1
0
    def generate_union(
        elements: typing.List,
        default: typing.Any = None,
        default_factory: typing.Callable = dataclasses.MISSING,
    ):
        """
        Generate union.

        Arguments:
            elements (typing.List): List of python types
            default (typing.Any): Default value
            default factory (typing.Calleable): Callable to get the default value for
                a list or dict type

        Returns:
            typing.List: List of avro types
        """
        unions = []
        for element in elements:
            if element in PRIMITIVE_AND_LOGICAL_TYPES:
                klass = PRIMITIVE_LOGICAL_TYPES_FIELDS_CLASSES[element]
                union_element = klass.avro_type
            else:
                union_element = schema_generator.SchemaGenerator(
                    element
                ).avro_schema_to_python()

            unions.append(union_element)

        if default is None and default_factory is dataclasses.MISSING:
            unions.insert(0, NULL)

        return unions
Exemplo n.º 2
0
    def generate_values_type(self):
        """
        Process typing.Dict. Avro assumes that the key of a map is always a string,
        so we take the second argument to determine the value type
        """
        values_type = self.type.__args__[1]

        if values_type in PRIMITIVE_AND_LOGICAL_TYPES:
            klass = PRIMITIVE_LOGICAL_TYPES_FIELDS_CLASSES[values_type]
            self.values_type = klass.avro_type
        elif utils.is_self_referenced(values_type):
            # Checking for a self reference. Maybe is a typing.ForwardRef
            self.values_type = self._get_self_reference_type(values_type)
        else:
            self.values_type = schema_generator.SchemaGenerator(
                values_type).avro_schema_to_python()
Exemplo n.º 3
0
    def generate_items_type(self):
        # because avro can have only one type, we take the first one
        items_type = self.type.__args__[0]

        if items_type in PRIMITIVE_AND_LOGICAL_TYPES:
            klass = PRIMITIVE_LOGICAL_TYPES_FIELDS_CLASSES[items_type]
            self.items_type = klass.avro_type
        elif utils.is_self_referenced(items_type):
            # Checking for a self reference. Maybe is a typing.ForwardRef
            self.items_type = self._get_self_reference_type(items_type)
        elif utils.is_union(items_type):
            self.items_type = UnionField.generate_union(
                items_type.__args__,
                default=self.default,
                default_factory=self.default_factory,
            )
        else:
            # Is Avro Record Type
            self.items_type = schema_generator.SchemaGenerator(
                items_type).avro_schema_to_python()
Exemplo n.º 4
0
 def get_avro_type(self):
     return schema_generator.SchemaGenerator(self.type).avro_schema_to_python()