Skip to content

config

xsdata.models.config

StructureStyle

Bases: Enum

Output structure style enumeration.

Attributes:

Name Type Description
FILENAMES

filenames: groups classes by the schema location

NAMESPACES

namespaces: group classes by the target namespace

CLUSTERS

clusters: group by strong connected dependencies

SINGLE_PACKAGE

single-package: group all classes together

NAMESPACE_CLUSTERS

namespace-clusters: group by strong connected dependencies and namespaces

Source code in xsdata/models/config.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class StructureStyle(Enum):
    """Output structure style enumeration.

    Attributes:
        FILENAMES: filenames: groups classes by the schema location
        NAMESPACES: namespaces: group classes by the target namespace
        CLUSTERS: clusters: group by strong connected dependencies
        SINGLE_PACKAGE: single-package: group all classes together
        NAMESPACE_CLUSTERS: namespace-clusters: group by strong
            connected dependencies and namespaces
    """

    FILENAMES = "filenames"
    NAMESPACES = "namespaces"
    CLUSTERS = "clusters"
    SINGLE_PACKAGE = "single-package"
    NAMESPACE_CLUSTERS = "namespace-clusters"

NameCase

Bases: Enum

Naming case convention enumeration.

All schemes are using a processor that splits a string into words when it encounters non-alphanumerical characters or when an upper case letter follows a lower case letter.

Attributes:

Name Type Description
ORIGINAL

originalCase

PASCAL

pascalCase

CAMEL

camelCase

SNAKE

snakeCase

SCREAMING_SNAKE

screamingSnakeCase

MIXED

mixedCase

MIXED_SNAKE

mixedSnakeCase

MIXED_PASCAL

mixedPascalCase

Source code in xsdata/models/config.py
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
class NameCase(Enum):
    """Naming case convention enumeration.

    All schemes are using a processor that splits a string into words
    when it encounters non-alphanumerical characters or when an upper
    case letter follows a lower case letter.

    Attributes:
        ORIGINAL: originalCase
        PASCAL: pascalCase
        CAMEL: camelCase
        SNAKE: snakeCase
        SCREAMING_SNAKE: screamingSnakeCase
        MIXED: mixedCase
        MIXED_SNAKE: mixedSnakeCase
        MIXED_PASCAL: mixedPascalCase
    """

    ORIGINAL = "originalCase"
    PASCAL = "pascalCase"
    CAMEL = "camelCase"
    SNAKE = "snakeCase"
    SCREAMING_SNAKE = "screamingSnakeCase"
    MIXED = "mixedCase"
    MIXED_SNAKE = "mixedSnakeCase"
    MIXED_PASCAL = "mixedPascalCase"

    def __call__(self, string: str, **kwargs: Any) -> str:
        """Apply the callback to the input string."""
        return self.callback(string, **kwargs)

    @property
    def callback(self) -> Callable:
        """Return the actual callable of the scheme."""
        return __name_case_func__[self.value]

callback: Callable property

Return the actual callable of the scheme.

__call__(string, **kwargs)

Apply the callback to the input string.

Source code in xsdata/models/config.py
68
69
70
def __call__(self, string: str, **kwargs: Any) -> str:
    """Apply the callback to the input string."""
    return self.callback(string, **kwargs)

DocstringStyle

Bases: Enum

Docstring style enumeration.

Attributes:

Name Type Description
RST

reStructuredText

NUMPY

NumPy

GOOGLE

Google

ACCESSIBLE

Accessible

BLANK

Blank

Source code in xsdata/models/config.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
class DocstringStyle(Enum):
    """Docstring style enumeration.

    Attributes:
        RST: reStructuredText
        NUMPY: NumPy
        GOOGLE: Google
        ACCESSIBLE: Accessible
        BLANK: Blank
    """

    RST = "reStructuredText"
    NUMPY = "NumPy"
    GOOGLE = "Google"
    ACCESSIBLE = "Accessible"
    BLANK = "Blank"

ObjectType

Bases: Enum

Object type enumeration.

Attributes:

Name Type Description
CLASS

class

FIELD

field

MODULE

module

PACKAGE

package

Source code in xsdata/models/config.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class ObjectType(Enum):
    """Object type enumeration.

    Attributes:
        CLASS: class
        FIELD: field
        MODULE: module
        PACKAGE: package
    """

    CLASS = "class"
    FIELD = "field"
    MODULE = "module"
    PACKAGE = "package"

ExtensionType

Bases: Enum

Extension type enumeration.

Attributes:

Name Type Description
CLASS

class

DECORATOR

decorator

Source code in xsdata/models/config.py
124
125
126
127
128
129
130
131
132
133
class ExtensionType(Enum):
    """Extension type enumeration.

    Attributes:
        CLASS: class
        DECORATOR: decorator
    """

    CLASS = "class"
    DECORATOR = "decorator"

OutputFormat dataclass

Output format model representation.

Parameters:

Name Type Description Default
value str

Output format name

text_node(default='dataclasses', cli='output')
repr bool

Generate repr method

attribute(default=True)
eq bool

Generate eq method

attribute(default=True)
order bool

Generate lt, le, gt, and ge methods

attribute(default=False)
unsafe_hash bool

Generate hash method

attribute(default=False)
frozen bool

Enable read only properties

attribute(default=False)
slots bool

Enable slots, python>=3.10 Only

attribute(default=False)
kw_only bool

Enable keyword only arguments, python>=3.10 Only

attribute(default=False)
Source code in xsdata/models/config.py
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
@dataclass
class OutputFormat:
    """Output format model representation.

    Args:
        value: Output format name
        repr: Generate __repr__ method
        eq: Generate __eq__ method
        order: Generate __lt__, __le__, __gt__, and __ge__ methods
        unsafe_hash: Generate __hash__ method
        frozen: Enable read only properties
        slots: Enable __slots__, python>=3.10 Only
        kw_only: Enable keyword only arguments, python>=3.10 Only
    """

    value: str = text_node(default="dataclasses", cli="output")
    repr: bool = attribute(default=True)
    eq: bool = attribute(default=True)
    order: bool = attribute(default=False)
    unsafe_hash: bool = attribute(default=False)
    frozen: bool = attribute(default=False)
    slots: bool = attribute(default=False)
    kw_only: bool = attribute(default=False)

    def __post_init__(self):
        """Post initialization method."""
        self.validate()

    def validate(self):
        """Validate and reset configuration conflicts."""
        if self.order and not self.eq:
            self.eq = True
            warnings.warn(
                "Enabling eq because order is true",
                CodegenWarning,
            )

        if self.value == "dataclasses" and sys.version_info < (3, 10):
            if self.slots:
                self.slots = False
                warnings.warn(
                    "slots requires python >= 3.10, reverting...",
                    CodegenWarning,
                )

            if self.kw_only:
                self.kw_only = False
                warnings.warn(
                    "kw_only requires python >= 3.10, reverting...",
                    CodegenWarning,
                )

__post_init__()

Post initialization method.

Source code in xsdata/models/config.py
160
161
162
def __post_init__(self):
    """Post initialization method."""
    self.validate()

validate()

Validate and reset configuration conflicts.

Source code in xsdata/models/config.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def validate(self):
    """Validate and reset configuration conflicts."""
    if self.order and not self.eq:
        self.eq = True
        warnings.warn(
            "Enabling eq because order is true",
            CodegenWarning,
        )

    if self.value == "dataclasses" and sys.version_info < (3, 10):
        if self.slots:
            self.slots = False
            warnings.warn(
                "slots requires python >= 3.10, reverting...",
                CodegenWarning,
            )

        if self.kw_only:
            self.kw_only = False
            warnings.warn(
                "kw_only requires python >= 3.10, reverting...",
                CodegenWarning,
            )

CompoundFields dataclass

Compound fields model representation.

Parameters:

Name Type Description Default
enabled bool

Use compound fields for repeatable elements

text_node(default=False, cli='compound-fields')
default_name str

Default compound field name

attribute(default='choice', cli=False)
use_substitution_groups bool

Use substitution groups if they exist, instead of element names.

attribute(default=False, cli=False)
force_default_name bool

Always use the default compound field name, or try to generate one by the list of element names if they are no longer than the max name parts. e.g. hat_or_dress_or_something.

attribute(default=False, cli=False)
max_name_parts int

Maximum number of element names before using the default name.

attribute(default=3, cli=False)
Source code in xsdata/models/config.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@dataclass
class CompoundFields:
    """Compound fields model representation.

    Args:
        enabled: Use compound fields for repeatable elements
        default_name: Default compound field name
        use_substitution_groups: Use substitution groups if they
            exist, instead of element names.
        force_default_name: Always use the default compound field
            name, or try to generate one by the list of element names if
            they are no longer than the max name parts. e.g.
            hat_or_dress_or_something.
        max_name_parts: Maximum number of element names before using
            the default name.
    """

    enabled: bool = text_node(default=False, cli="compound-fields")
    default_name: str = attribute(default="choice", cli=False)
    use_substitution_groups: bool = attribute(default=False, cli=False)
    force_default_name: bool = attribute(default=False, cli=False)
    max_name_parts: int = attribute(default=3, cli=False)

GeneratorOutput dataclass

Generator output model representation.

Parameters:

Name Type Description Default
package str

Target package

element(default='generated')
format OutputFormat

Output format

element(default_factory=OutputFormat)
structure_style StructureStyle

Output structure style

element(default=FILENAMES, name='Structure')
docstring_style DocstringStyle

Docstring style

element(default=RST)
relative_imports bool

Use relative imports

element(default=False)
compound_fields CompoundFields

Use compound fields for repeatable elements

element(default_factory=CompoundFields)
wrapper_fields bool

Generate wrapper fields

element(default=False)
max_line_length int

Adjust the maximum line length

attribute(default=79)
subscriptable_types bool

Use PEP-585 generics for standard collections, python>=3.9 Only

attribute(default=False)
union_type bool

Use PEP-604 union type, python>=3.10 Only

attribute(default=False)
postponed_annotations bool

Use 563 postponed evaluation of annotations

element(default=False)
unnest_classes bool

Move inner classes to upper level

element(default=False)
ignore_patterns bool

Ignore pattern restrictions

element(default=False)
include_header bool

Include a header with codegen information in the output

element(default=False)
Source code in xsdata/models/config.py
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
@dataclass
class GeneratorOutput:
    """Generator output model representation.

    Args:
        package: Target package
        format: Output format
        structure_style: Output structure style
        docstring_style: Docstring style
        relative_imports: Use relative imports
        compound_fields: Use compound fields for repeatable elements
        wrapper_fields: Generate wrapper fields
        max_line_length: Adjust the maximum line length
        subscriptable_types: Use PEP-585 generics for standard
            collections, python>=3.9 Only
        union_type: Use PEP-604 union type, python>=3.10 Only
        postponed_annotations: Use 563 postponed evaluation of  annotations
        unnest_classes: Move inner classes to upper level
        ignore_patterns: Ignore pattern restrictions
        include_header: Include a header with codegen information in the output
    """

    package: str = element(default="generated")
    format: OutputFormat = element(default_factory=OutputFormat)
    structure_style: StructureStyle = element(
        default=StructureStyle.FILENAMES, name="Structure"
    )
    docstring_style: DocstringStyle = element(default=DocstringStyle.RST)
    relative_imports: bool = element(default=False)
    compound_fields: CompoundFields = element(default_factory=CompoundFields)
    wrapper_fields: bool = element(default=False)
    max_line_length: int = attribute(default=79)
    subscriptable_types: bool = attribute(default=False)
    union_type: bool = attribute(default=False)
    postponed_annotations: bool = element(default=False)
    unnest_classes: bool = element(default=False)
    ignore_patterns: bool = element(default=False)
    include_header: bool = element(default=False)

    def __post_init__(self):
        """Post initialization method."""
        self.validate()

    def validate(self):
        """Reset configuration conflicts."""
        if self.subscriptable_types and sys.version_info < (3, 9):
            self.subscriptable_types = False
            warnings.warn(
                "Generics PEP 585 requires python >= 3.9, reverting...",
                CodegenWarning,
            )

        if self.union_type and sys.version_info < (3, 10):
            self.union_type = False
            warnings.warn(
                "UnionType PEP 604 requires python >= 3.10, reverting...",
                CodegenWarning,
            )

        if self.union_type and not self.postponed_annotations:
            self.postponed_annotations = True
            warnings.warn(
                "Enabling postponed annotations, because `union_type==True`",
                CodegenWarning,
            )

    def update(self, **kwargs: Any):
        """Update instance attributes recursively."""
        objects.update(self, **kwargs)
        self.format.validate()

__post_init__()

Post initialization method.

Source code in xsdata/models/config.py
252
253
254
def __post_init__(self):
    """Post initialization method."""
    self.validate()

validate()

Reset configuration conflicts.

Source code in xsdata/models/config.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def validate(self):
    """Reset configuration conflicts."""
    if self.subscriptable_types and sys.version_info < (3, 9):
        self.subscriptable_types = False
        warnings.warn(
            "Generics PEP 585 requires python >= 3.9, reverting...",
            CodegenWarning,
        )

    if self.union_type and sys.version_info < (3, 10):
        self.union_type = False
        warnings.warn(
            "UnionType PEP 604 requires python >= 3.10, reverting...",
            CodegenWarning,
        )

    if self.union_type and not self.postponed_annotations:
        self.postponed_annotations = True
        warnings.warn(
            "Enabling postponed annotations, because `union_type==True`",
            CodegenWarning,
        )

update(**kwargs)

Update instance attributes recursively.

Source code in xsdata/models/config.py
279
280
281
282
def update(self, **kwargs: Any):
    """Update instance attributes recursively."""
    objects.update(self, **kwargs)
    self.format.validate()

NameConvention dataclass

Name convention model representation.

Parameters:

Name Type Description Default
case NameCase

Naming scheme, e.g. camelCase, snakeCase

attribute(optional=False)
safe_prefix str

A prefix to be prepended into names that match one of the reserved words.

attribute(optional=False)
Source code in xsdata/models/config.py
285
286
287
288
289
290
291
292
293
294
295
296
@dataclass
class NameConvention:
    """Name convention model representation.

    Args:
        case: Naming scheme, e.g. camelCase, snakeCase
        safe_prefix: A prefix to be prepended into names that match
            one of the reserved words.
    """

    case: NameCase = attribute(optional=False)
    safe_prefix: str = attribute(optional=False)

GeneratorConventions dataclass

Generator naming conventions model representation.

Parameters:

Name Type Description Default
class_name NameConvention

Class naming conventions.

element(default_factory=lambda: NameConvention(PASCAL, 'type'))
field_name NameConvention

Field naming conventions.

element(default_factory=lambda: NameConvention(SNAKE, 'value'))
module_name NameConvention

Module naming conventions.

element(default_factory=lambda: NameConvention(SNAKE, 'mod'))
package_name NameConvention

Package naming conventions.

element(default_factory=lambda: NameConvention(SNAKE, 'pkg'))
Source code in xsdata/models/config.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
@dataclass
class GeneratorConventions:
    """Generator naming conventions model representation.

    Args:
        class_name: Class naming conventions.
        field_name: Field naming conventions.
        module_name: Module naming conventions.
        package_name: Package naming conventions.
    """

    class_name: NameConvention = element(
        default_factory=lambda: NameConvention(NameCase.PASCAL, "type")
    )
    field_name: NameConvention = element(
        default_factory=lambda: NameConvention(NameCase.SNAKE, "value")
    )
    constant_name: NameConvention = element(
        default_factory=lambda: NameConvention(NameCase.SCREAMING_SNAKE, "value")
    )
    module_name: NameConvention = element(
        default_factory=lambda: NameConvention(NameCase.SNAKE, "mod")
    )
    package_name: NameConvention = element(
        default_factory=lambda: NameConvention(NameCase.SNAKE, "pkg")
    )

GeneratorAlias dataclass

Generator alias model representation.

Define an alias for a module, package, class and field Alias definition model.

Each alias has a source attribute that refers to the original name in the schema definition and the target attribute for output name. For package and module aliases the source refers to the schema filename or target namespace depending on the selected output structure.

Parameters:

Name Type Description Default
source str

The source name from schema definition

attribute(required=True)
target str

The target name of the object.

attribute(required=True)
Source code in xsdata/models/config.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
@dataclass
class GeneratorAlias:
    """Generator alias model representation.

    Define an alias for a module, package, class and field Alias definition
    model.

    Each alias has a source attribute that refers to the original name
    in the schema definition and the target attribute for output name.
    For package and module aliases the source refers to the schema
    filename or target namespace depending on the selected output
    structure.

    Args:
        source: The source name from schema definition
        target: The target name of the object.
    """

    source: str = attribute(required=True)
    target: str = attribute(required=True)

GeneratorAliases dataclass

Generator aliases model representation.

Generator aliases for classes, fields, packages and modules that bypass the global naming conventions. The aliases are not validated as valid python identifiers.

Parameters:

Name Type Description Default
class_name List[GeneratorAlias]

A list of class name aliases

array_element()
field_name List[GeneratorAlias]

A list of field name aliases

array_element()
package_name List[GeneratorAlias]

A list of package name aliases

array_element()
module_name List[GeneratorAlias]

A list of module name aliases

array_element()
Source code in xsdata/models/config.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
@dataclass
class GeneratorAliases:
    """Generator aliases model representation.

    Generator aliases for classes, fields, packages and modules
    that bypass the global naming conventions. The aliases
    are not validated as valid python identifiers.

    Args:
        class_name: A list of class name aliases
        field_name: A list of field name aliases
        package_name: A list of package name aliases
        module_name: A list of module name aliases
    """

    class_name: List[GeneratorAlias] = array_element()
    field_name: List[GeneratorAlias] = array_element()
    package_name: List[GeneratorAlias] = array_element()
    module_name: List[GeneratorAlias] = array_element()

GeneratorSubstitution dataclass

Generator substitution model representation.

Search and replace substitutions based on re.sub.

Parameters:

Name Type Description Default
type ObjectType

The target object type

attribute(required=True)
search str

The search string or a pattern object

attribute(required=True)
replace str

The replacement string or pattern object

attribute(required=True)
Source code in xsdata/models/config.py
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
@dataclass
class GeneratorSubstitution:
    """Generator substitution model representation.

    Search and replace substitutions based on `re.sub`.

    Args:
        type: The target object type
        search: The search string or a pattern object
        replace: The replacement string or pattern object
    """

    type: ObjectType = attribute(required=True)
    search: str = attribute(required=True)
    replace: str = attribute(required=True)

GeneratorExtension dataclass

Generator extension model representation.

Add decorators or base classes on the generated classes that match the class name pattern.

Parameters:

Name Type Description Default
type ExtensionType

The extension type

attribute(required=True)
class_name str

The class name or a pattern to apply the extension

attribute(required=True, name='class')
import_string str

The import string of the extension type

attribute(required=True, name='import')
prepend bool

Prepend or append decorator or base class

attribute(default=False)
apply_if_derived bool

Apply or skip if the class is already a subclass

attribute(default=False, name='applyIfDerived')

Attributes:

Name Type Description
module_path str

The module path of the base class or the annotation

func_name str

The annotation or base class name

pattern Pattern

The compiled search class name pattern

Source code in xsdata/models/config.py
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
@dataclass
class GeneratorExtension:
    """Generator extension model representation.

    Add decorators or base classes on the generated classes
    that match the class name pattern.

    Args:
        type: The extension type
        class_name: The class name or a pattern to apply the extension
        import_string: The import string of the extension type
        prepend: Prepend or append decorator or base class
        apply_if_derived: Apply or skip if the class is already a subclass

    Attributes:
        module_path: The module path of the base class or the annotation
        func_name: The annotation or base class name
        pattern: The compiled search class name pattern
    """

    type: ExtensionType = attribute(required=True)
    class_name: str = attribute(required=True, name="class")
    import_string: str = attribute(required=True, name="import")
    prepend: bool = attribute(default=False)
    apply_if_derived: bool = attribute(default=False, name="applyIfDerived")

    module_path: str = field(
        init=False,
        metadata={"type": "Ignore"},
    )
    func_name: str = field(
        init=False,
        metadata={"type": "Ignore"},
    )
    pattern: Pattern = field(
        init=False,
        metadata={"type": "Ignore"},
    )

    def __post_init__(self):
        """Post initialization method.

        Set the module, func_name and pattern instance attributes.

        Raises:
            GeneratorConfigError: If the pattern can not be compiled.
        """
        try:
            self.module_path, self.func_name = self.import_string.rsplit(".", 1)
        except (ValueError, AttributeError):
            raise CodegenError(
                "Invalid extension import string", value=self.import_string
            )

        try:
            self.pattern = re.compile(self.class_name)
        except re.error:
            raise CodegenError(
                "Failed to compile extension pattern", pattern=self.class_name
            )

__post_init__()

Post initialization method.

Set the module, func_name and pattern instance attributes.

Raises:

Type Description
GeneratorConfigError

If the pattern can not be compiled.

Source code in xsdata/models/config.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def __post_init__(self):
    """Post initialization method.

    Set the module, func_name and pattern instance attributes.

    Raises:
        GeneratorConfigError: If the pattern can not be compiled.
    """
    try:
        self.module_path, self.func_name = self.import_string.rsplit(".", 1)
    except (ValueError, AttributeError):
        raise CodegenError(
            "Invalid extension import string", value=self.import_string
        )

    try:
        self.pattern = re.compile(self.class_name)
    except re.error:
        raise CodegenError(
            "Failed to compile extension pattern", pattern=self.class_name
        )

GeneratorSubstitutions dataclass

Generator substitutions model representation.

Generator search and replace substitutions for classes, fields, packages and modules names. The process runs before and after the default naming conventions.

Parameters:

Name Type Description Default
substitution List[GeneratorSubstitution]

The list of substitution instances

array_element()
Source code in xsdata/models/config.py
449
450
451
452
453
454
455
456
457
458
459
460
461
@dataclass
class GeneratorSubstitutions:
    """Generator substitutions model representation.

    Generator search and replace substitutions for classes, fields, packages
    and modules names. The process runs before and after the default naming
    conventions.

    Args:
        substitution: The list of substitution instances
    """

    substitution: List[GeneratorSubstitution] = array_element()

GeneratorExtensions dataclass

Generator extensions model representation.

Generator extensions for classes. The process runs after the default naming conventions. The generator doesn't validate imports!

Parameters:

Name Type Description Default
extension List[GeneratorExtension]

The list of extension instances

array_element()
Source code in xsdata/models/config.py
464
465
466
467
468
469
470
471
472
473
474
475
476
@dataclass
class GeneratorExtensions:
    """Generator extensions model representation.

    Generator extensions for classes. The process runs after the
    default naming conventions. The generator doesn't validate
    imports!

    Args:
        extension: The list of extension instances
    """

    extension: List[GeneratorExtension] = array_element()

GeneratorConfig dataclass

Generator configuration model representation.

Parameters:

Name Type Description Default
output GeneratorOutput

Output options

element(default_factory=GeneratorOutput)
conventions GeneratorConventions

Generator conventions

element(default_factory=GeneratorConventions)
substitutions GeneratorSubstitutions

Search and replace substitutions for classes, fields, packages and modules names.

element(default_factory=GeneratorSubstitutions)
extensions GeneratorExtensions

Generator custom base classes and decorators for classes.

element(default_factory=GeneratorExtensions)

Attributes:

Name Type Description
version str

The xsdata version number the config was created/updated

Source code in xsdata/models/config.py
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
@dataclass
class GeneratorConfig:
    """Generator configuration model representation.

    Args:
        output: Output options
        conventions: Generator conventions
        substitutions: Search and replace substitutions for
            classes, fields, packages and modules names.
        extensions: Generator custom base classes and decorators for classes.

    Attributes:
        version: The xsdata version number the config was created/updated
    """

    class Meta:
        """Metadata options."""

        name = "Config"
        namespace = "http://pypi.org/project/xsdata"

    version: str = attribute(default=__version__)
    output: GeneratorOutput = element(default_factory=GeneratorOutput)
    conventions: GeneratorConventions = element(default_factory=GeneratorConventions)
    substitutions: GeneratorSubstitutions = element(
        default_factory=GeneratorSubstitutions
    )
    extensions: GeneratorExtensions = element(default_factory=GeneratorExtensions)

    @classmethod
    def create(cls) -> "GeneratorConfig":
        """Initialize with default substitutions for common namespaces."""
        obj = cls()

        for ns in Namespace:
            obj.substitutions.substitution.append(
                GeneratorSubstitution(
                    type=ObjectType.PACKAGE, search=ns.uri, replace=ns.prefix
                )
            )

        obj.substitutions.substitution.append(
            GeneratorSubstitution(
                type=ObjectType.CLASS, search="(.*)Class$", replace="\\1Type"
            )
        )

        return obj

    @classmethod
    def read(cls, path: Path) -> "GeneratorConfig":
        """Load configuration from a file path."""
        if not path.exists():
            return cls()

        ctx = XmlContext(
            element_name_generator=text.pascal_case,
            attribute_name_generator=text.camel_case,
        )
        parser = XmlParser(
            context=ctx,
            config=ParserConfig(
                fail_on_unknown_properties=False,
                fail_on_converter_warnings=True,
            ),
        )
        cfg = parser.from_path(path, cls)
        cfg.version = __version__
        return cfg

    @classmethod
    def write(cls, output: TextIO, obj: "GeneratorConfig"):
        """Write the configuration to the output stream as xml."""
        ctx = XmlContext(
            element_name_generator=text.pascal_case,
            attribute_name_generator=text.camel_case,
        )
        config = SerializerConfig(indent="  ")
        serializer = XmlSerializer(context=ctx, config=config, writer=XmlEventWriter)
        serializer.write(output, obj, ns_map={None: "http://pypi.org/project/xsdata"})

Meta

Metadata options.

Source code in xsdata/models/config.py
494
495
496
497
498
class Meta:
    """Metadata options."""

    name = "Config"
    namespace = "http://pypi.org/project/xsdata"

create() classmethod

Initialize with default substitutions for common namespaces.

Source code in xsdata/models/config.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
@classmethod
def create(cls) -> "GeneratorConfig":
    """Initialize with default substitutions for common namespaces."""
    obj = cls()

    for ns in Namespace:
        obj.substitutions.substitution.append(
            GeneratorSubstitution(
                type=ObjectType.PACKAGE, search=ns.uri, replace=ns.prefix
            )
        )

    obj.substitutions.substitution.append(
        GeneratorSubstitution(
            type=ObjectType.CLASS, search="(.*)Class$", replace="\\1Type"
        )
    )

    return obj

read(path) classmethod

Load configuration from a file path.

Source code in xsdata/models/config.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
@classmethod
def read(cls, path: Path) -> "GeneratorConfig":
    """Load configuration from a file path."""
    if not path.exists():
        return cls()

    ctx = XmlContext(
        element_name_generator=text.pascal_case,
        attribute_name_generator=text.camel_case,
    )
    parser = XmlParser(
        context=ctx,
        config=ParserConfig(
            fail_on_unknown_properties=False,
            fail_on_converter_warnings=True,
        ),
    )
    cfg = parser.from_path(path, cls)
    cfg.version = __version__
    return cfg

write(output, obj) classmethod

Write the configuration to the output stream as xml.

Source code in xsdata/models/config.py
549
550
551
552
553
554
555
556
557
558
@classmethod
def write(cls, output: TextIO, obj: "GeneratorConfig"):
    """Write the configuration to the output stream as xml."""
    ctx = XmlContext(
        element_name_generator=text.pascal_case,
        attribute_name_generator=text.camel_case,
    )
    config = SerializerConfig(indent="  ")
    serializer = XmlSerializer(context=ctx, config=config, writer=XmlEventWriter)
    serializer.write(output, obj, ns_map={None: "http://pypi.org/project/xsdata"})