Skip to content

# generator

## `xsdata.formats.dataclass.generator`

### `DataclassGenerator`

Bases: `AbstractGenerator`

Python dataclasses code generator.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`config` | `GeneratorConfig` | The generator config instance | required

Attributes:

Name | Type | Description
--- | --- | ---
`env` |  | The jinja2 environment instance
`filters` |  | The template filters instance

Source code in `xsdata/formats/dataclass/generator.py`

     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     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
     91
     92
     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

    class DataclassGenerator(AbstractGenerator):
        """Python dataclasses code generator.

        Args:
            config: The generator config instance

        Attributes:
            env: The jinja2 environment instance
            filters: The template filters instance
        """

        __slots__ = ("env", "filters")

        package_template = "package.jinja2"
        module_template = "module.jinja2"
        enum_template = "enum.jinja2"
        service_template = "service.jinja2"
        class_template = "class.jinja2"

        def __init__(self, config: GeneratorConfig):
            """Initialize the generator."""
            super().__init__(config)
            template_paths = self.get_template_paths()
            loader = FileSystemLoader(template_paths)
            self.env = Environment(loader=loader, autoescape=False)
            self.filters = self.init_filters(config)
            self.filters.register(self.env)

        @classmethod
        def get_template_paths(cls) -> list[str]:
            """Return a list of template paths to feed the jinja2 loader."""
            return [str(Path(__file__).parent.joinpath("templates"))]

        def render(self, classes: list[Class]) -> Iterator[GeneratorResult]:
            """Render the given classes to python packages and modules.

            Args:
                  classes: A list of class instances

            Yields:
                An iterator of generator result instances.
            """
            packages = {obj.qname: obj.target_module for obj in classes}
            resolver = DependenciesResolver(registry=packages)
            package_dirs = set()
            # Generate packages
            for path, cluster in self.group_by_package(classes).items():
                module = ".".join(path.relative_to(Path.cwd()).parts)
                package_path = path.joinpath("__init__.py")
                src_code = self.render_package(cluster, module)
                package_dirs.add(str(path))

                yield GeneratorResult(
                    path=package_path,
                    title="init",
                    source=src_code,
                )
                yield from self.ensure_packages(path.parent)

            # Generate modules
            for path, cluster in self.group_by_module(classes).items():
                module_path = path.with_suffix(".py")
                src_code = self.render_module(resolver, cluster)

                yield GeneratorResult(
                    path=module_path,
                    title=cluster[0].target_module,
                    source=src_code,
                )

            self.ruff_code(list(package_dirs))
            self.validate_imports()

        def validate_imports(self) -> None:
            """Recursively import all generated packages.

            Raises:
                ImportError: On circular imports
            """

            def import_package(package_name: str) -> None:
                logger.debug(f"Importing: {package_name}")
                module = importlib.import_module(package_name)
                if hasattr(module, "__path__"):
                    for _, name, _ in pkgutil.walk_packages(
                        module.__path__, module.__name__ + "."
                    ):
                        logger.debug(f"Importing: {name}")
                        importlib.import_module(name)

            sys.path.insert(0, str(Path.cwd().absolute()))
            package = self.config.output.package
            import_package(self.package_name(package))

        def render_package(self, classes: list[Class], module: str) -> str:
            """Render the package for the given classes.

            Args:
                classes: A list of class instances
                module: The target dot notation path

            Returns:
                The rendered package output.
            """
            imports = [
                Import(qname=obj.qname, source=obj.target_module)
                for obj in sorted(classes, key=lambda x: x.name)
            ]
            DependenciesResolver.resolve_conflicts(imports, set())

            return self.env.get_template(self.package_template).render(
                imports=imports,
                module=module,
            )

        def render_module(
            self,
            resolver: DependenciesResolver,
            classes: list[Class],
        ) -> str:
            """Render the module for the given classes.

            Args:
                resolver: The dependencies resolver
                classes: A list of class instances

            Returns:
                The rendered module output.
            """
            if len({x.target_namespace for x in classes}) == 1:
                module_namespace = classes[0].target_namespace
            else:
                module_namespace = None

            resolver.process(classes)
            imports = resolver.sorted_imports()
            classes = resolver.sorted_classes()
            output = self.render_classes(classes, module_namespace)
            module = classes[0].target_module

            return self.env.get_template(self.module_template).render(
                output=output,
                classes=classes,
                module=module,
                imports=imports,
                namespace=module_namespace,
            )

        def render_classes(
            self,
            classes: list[Class],
            module_namespace: str | None,
        ) -> str:
            """Render the classes source code in a module.

            Args:
                classes: A list of class instances
                module_namespace: The module namespace URI

            Returns:
                The rendered classes source code output.
            """

            def render_class(obj: Class) -> str:
                """Render class or enumeration."""
                if obj.is_enumeration:
                    template = self.enum_template
                elif obj.is_service:
                    template = self.service_template
                else:
                    template = self.class_template

                return (
                    self.env.get_template(template)
                    .render(
                        obj=obj,
                        module_namespace=module_namespace,
                    )
                    .strip()
                )

            return "\n".join(map(render_class, classes))

        def module_name(self, name: str) -> str:
            """Convert the given module name to safe snake case."""
            return self.filters.module_name(name)

        def package_name(self, name: str) -> str:
            """Convert the given package name to safe snake case."""
            return self.filters.package_name(name)

        @classmethod
        def ensure_packages(cls, package: Path) -> Iterator[GeneratorResult]:
            """Ensure __init__.py files exists recursively in the package.

            Args:
                package: The package file path

            Yields:
                An iterator of generator result instances.
            """
            cwd = Path.cwd()
            while cwd < package:
                init = package.joinpath("__init__.py")
                if not init.exists():
                    yield GeneratorResult(
                        path=init, title="init", source="# nothing here\n"
                    )
                package = package.parent

        @classmethod
        def init_filters(cls, config: GeneratorConfig) -> Filters:
            """Initialize the filters instance by the generator configuration."""
            return Filters(config)

        def ruff_code(self, file_paths: list[str]) -> None:
            """Run ruff lint and format on a list of file names.

            Args:
                file_paths: A list of files/directories to format and check
            """
            ruff_config = Path(__file__).parent.joinpath("ruff.toml")
            commands = [
                [
                    "ruff",
                    "check",
                    "--config",
                    str(ruff_config),
                    "--config",
                    f"line-length={self.config.output.max_line_length}",
                    "--fix",
                    "--unsafe-fixes",
                    "--exit-zero",
                    *file_paths,
                ],
                [
                    "ruff",
                    "format",
                    "--config",
                    str(ruff_config),
                    "--config",
                    f"line-length={self.config.output.max_line_length}",
                    *file_paths,
                ],
            ]

            # override to replace ruff with black
            # remove when a less ancient ruff gets into Debian (#1068248)
            commands = [
                [
                    "black",
                    f"--line-length={self.config.output.max_line_length}",
                    *file_paths,
                ],
            ]

            try:
                for command in commands:
                    subprocess.run(
                        command,
                        capture_output=True,
                        check=True,
                    )
            except subprocess.CalledProcessError as e:
                details = e.stderr.decode().replace("error: ", "").strip()
                raise CodegenError(f"Ruff failed\n{details}")

#### `__init__(config)`

Initialize the generator.

Source code in `xsdata/formats/dataclass/generator.py`

    38
    39
    40
    41
    42
    43
    44
    45

    def __init__(self, config: GeneratorConfig):
        """Initialize the generator."""
        super().__init__(config)
        template_paths = self.get_template_paths()
        loader = FileSystemLoader(template_paths)
        self.env = Environment(loader=loader, autoescape=False)
        self.filters = self.init_filters(config)
        self.filters.register(self.env)

#### `get_template_paths()` `classmethod`

Return a list of template paths to feed the jinja2 loader.

Source code in `xsdata/formats/dataclass/generator.py`

    47
    48
    49
    50

    @classmethod
    def get_template_paths(cls) -> list[str]:
        """Return a list of template paths to feed the jinja2 loader."""
        return [str(Path(__file__).parent.joinpath("templates"))]

#### `render(classes)`

Render the given classes to python packages and modules.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`classes` | `list[Class]` | A list of class instances | required

Yields:

Type | Description
--- | ---
`GeneratorResult` | An iterator of generator result instances.

Source code in `xsdata/formats/dataclass/generator.py`

    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

    def render(self, classes: list[Class]) -> Iterator[GeneratorResult]:
        """Render the given classes to python packages and modules.

        Args:
              classes: A list of class instances

        Yields:
            An iterator of generator result instances.
        """
        packages = {obj.qname: obj.target_module for obj in classes}
        resolver = DependenciesResolver(registry=packages)
        package_dirs = set()
        # Generate packages
        for path, cluster in self.group_by_package(classes).items():
            module = ".".join(path.relative_to(Path.cwd()).parts)
            package_path = path.joinpath("__init__.py")
            src_code = self.render_package(cluster, module)
            package_dirs.add(str(path))

            yield GeneratorResult(
                path=package_path,
                title="init",
                source=src_code,
            )
            yield from self.ensure_packages(path.parent)

        # Generate modules
        for path, cluster in self.group_by_module(classes).items():
            module_path = path.with_suffix(".py")
            src_code = self.render_module(resolver, cluster)

            yield GeneratorResult(
                path=module_path,
                title=cluster[0].target_module,
                source=src_code,
            )

        self.ruff_code(list(package_dirs))
        self.validate_imports()

#### `validate_imports()`

Recursively import all generated packages.

Raises:

Type | Description
--- | ---
`ImportError` | On circular imports

Source code in `xsdata/formats/dataclass/generator.py`

     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111

    def validate_imports(self) -> None:
        """Recursively import all generated packages.

        Raises:
            ImportError: On circular imports
        """

        def import_package(package_name: str) -> None:
            logger.debug(f"Importing: {package_name}")
            module = importlib.import_module(package_name)
            if hasattr(module, "__path__"):
                for _, name, _ in pkgutil.walk_packages(
                    module.__path__, module.__name__ + "."
                ):
                    logger.debug(f"Importing: {name}")
                    importlib.import_module(name)

        sys.path.insert(0, str(Path.cwd().absolute()))
        package = self.config.output.package
        import_package(self.package_name(package))

#### `render_package(classes, module)`

Render the package for the given classes.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`classes` | `list[Class]` | A list of class instances | required
`module` | `str` | The target dot notation path | required

Returns:

Type | Description
--- | ---
`str` | The rendered package output.

Source code in `xsdata/formats/dataclass/generator.py`

    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132

    def render_package(self, classes: list[Class], module: str) -> str:
        """Render the package for the given classes.

        Args:
            classes: A list of class instances
            module: The target dot notation path

        Returns:
            The rendered package output.
        """
        imports = [
            Import(qname=obj.qname, source=obj.target_module)
            for obj in sorted(classes, key=lambda x: x.name)
        ]
        DependenciesResolver.resolve_conflicts(imports, set())

        return self.env.get_template(self.package_template).render(
            imports=imports,
            module=module,
        )

#### `render_module(resolver, classes)`

Render the module for the given classes.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`resolver` | `DependenciesResolver` | The dependencies resolver | required
`classes` | `list[Class]` | A list of class instances | required

Returns:

Type | Description
--- | ---
`str` | The rendered module output.

Source code in `xsdata/formats/dataclass/generator.py`

    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

    def render_module(
        self,
        resolver: DependenciesResolver,
        classes: list[Class],
    ) -> str:
        """Render the module for the given classes.

        Args:
            resolver: The dependencies resolver
            classes: A list of class instances

        Returns:
            The rendered module output.
        """
        if len({x.target_namespace for x in classes}) == 1:
            module_namespace = classes[0].target_namespace
        else:
            module_namespace = None

        resolver.process(classes)
        imports = resolver.sorted_imports()
        classes = resolver.sorted_classes()
        output = self.render_classes(classes, module_namespace)
        module = classes[0].target_module

        return self.env.get_template(self.module_template).render(
            output=output,
            classes=classes,
            module=module,
            imports=imports,
            namespace=module_namespace,
        )

#### `render_classes(classes, module_namespace)`

Render the classes source code in a module.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`classes` | `list[Class]` | A list of class instances | required
`module_namespace` | `str | None` | The module namespace URI | required

Returns:

Type | Description
--- | ---
`str` | The rendered classes source code output.

Source code in `xsdata/formats/dataclass/generator.py`

    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

    def render_classes(
        self,
        classes: list[Class],
        module_namespace: str | None,
    ) -> str:
        """Render the classes source code in a module.

        Args:
            classes: A list of class instances
            module_namespace: The module namespace URI

        Returns:
            The rendered classes source code output.
        """

        def render_class(obj: Class) -> str:
            """Render class or enumeration."""
            if obj.is_enumeration:
                template = self.enum_template
            elif obj.is_service:
                template = self.service_template
            else:
                template = self.class_template

            return (
                self.env.get_template(template)
                .render(
                    obj=obj,
                    module_namespace=module_namespace,
                )
                .strip()
            )

        return "\n".join(map(render_class, classes))

#### `module_name(name)`

Convert the given module name to safe snake case.

Source code in `xsdata/formats/dataclass/generator.py`

    202
    203
    204

    def module_name(self, name: str) -> str:
        """Convert the given module name to safe snake case."""
        return self.filters.module_name(name)

#### `package_name(name)`

Convert the given package name to safe snake case.

Source code in `xsdata/formats/dataclass/generator.py`

    206
    207
    208

    def package_name(self, name: str) -> str:
        """Convert the given package name to safe snake case."""
        return self.filters.package_name(name)

#### `ensure_packages(package)` `classmethod`

Ensure init.py files exists recursively in the package.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`package` | `Path` | The package file path | required

Yields:

Type | Description
--- | ---
`GeneratorResult` | An iterator of generator result instances.

Source code in `xsdata/formats/dataclass/generator.py`

    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227

    @classmethod
    def ensure_packages(cls, package: Path) -> Iterator[GeneratorResult]:
        """Ensure __init__.py files exists recursively in the package.

        Args:
            package: The package file path

        Yields:
            An iterator of generator result instances.
        """
        cwd = Path.cwd()
        while cwd < package:
            init = package.joinpath("__init__.py")
            if not init.exists():
                yield GeneratorResult(
                    path=init, title="init", source="# nothing here\n"
                )
            package = package.parent

#### `init_filters(config)` `classmethod`

Initialize the filters instance by the generator configuration.

Source code in `xsdata/formats/dataclass/generator.py`

    229
    230
    231
    232

    @classmethod
    def init_filters(cls, config: GeneratorConfig) -> Filters:
        """Initialize the filters instance by the generator configuration."""
        return Filters(config)

#### `ruff_code(file_paths)`

Run ruff lint and format on a list of file names.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`file_paths` | `list[str]` | A list of files/directories to format and check | required

Source code in `xsdata/formats/dataclass/generator.py`

    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

    def ruff_code(self, file_paths: list[str]) -> None:
        """Run ruff lint and format on a list of file names.

        Args:
            file_paths: A list of files/directories to format and check
        """
        ruff_config = Path(__file__).parent.joinpath("ruff.toml")
        commands = [
            [
                "ruff",
                "check",
                "--config",
                str(ruff_config),
                "--config",
                f"line-length={self.config.output.max_line_length}",
                "--fix",
                "--unsafe-fixes",
                "--exit-zero",
                *file_paths,
            ],
            [
                "ruff",
                "format",
                "--config",
                str(ruff_config),
                "--config",
                f"line-length={self.config.output.max_line_length}",
                *file_paths,
            ],
        ]

        # override to replace ruff with black
        # remove when a less ancient ruff gets into Debian (#1068248)
        commands = [
            [
                "black",
                f"--line-length={self.config.output.max_line_length}",
                *file_paths,
            ],
        ]

        try:
            for command in commands:
                subprocess.run(
                    command,
                    capture_output=True,
                    check=True,
                )
        except subprocess.CalledProcessError as e:
            details = e.stderr.decode().replace("error: ", "").strip()
            raise CodegenError(f"Ruff failed\n{details}")