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
 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
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", "ruff_config")

    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):
        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)
        self.ruff_config = Path(__file__).parent / "ruff.toml"

    @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):
        """Recursively import all generated packages.

        Raises:
            ImportError: On circular imports
        """

        def import_package(package_name):
            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: Optional[str],
    ) -> 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]):
        """Run ruff lint and format on a list of file names.

        Args:
            file_paths: A list of files/directories to format and check
        """
        commands = [
            [
                "ruff",
                "format",
                "--line-length",
                str(self.config.output.max_line_length),
                *file_paths,
            ],
            [
                "ruff",
                "checks",
                "--line-length",
                str(self.config.output.max_line_length),
                "--config",
                str(self.ruff_config),
                "--fix",
                "--unsafe-fixes",
                "--exit-zero",
                *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}")

get_template_paths() classmethod

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

Source code in xsdata/formats/dataclass/generator.py
48
49
50
51
@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
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
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
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def validate_imports(self):
    """Recursively import all generated packages.

    Raises:
        ImportError: On circular imports
    """

    def import_package(package_name):
        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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
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
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 Optional[str]

The module namespace URI

required

Returns:

Type Description
str

The rendered classes source code output.

Source code in xsdata/formats/dataclass/generator.py
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
def render_classes(
    self,
    classes: List[Class],
    module_namespace: Optional[str],
) -> 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
203
204
205
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
207
208
209
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
@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
230
231
232
233
@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
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
def ruff_code(self, file_paths: List[str]):
    """Run ruff lint and format on a list of file names.

    Args:
        file_paths: A list of files/directories to format and check
    """
    commands = [
        [
            "ruff",
            "format",
            "--line-length",
            str(self.config.output.max_line_length),
            *file_paths,
        ],
        [
            "ruff",
            "checks",
            "--line-length",
            str(self.config.output.max_line_length),
            "--config",
            str(self.ruff_config),
            "--fix",
            "--unsafe-fixes",
            "--exit-zero",
            *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}")