Skip to content

container

xsdata.codegen.container

Steps

Process steps.

Source code in xsdata/codegen/container.py
39
40
41
42
43
44
45
46
47
class Steps:
    """Process steps."""

    UNGROUP = 10
    FLATTEN = 20
    SANITIZE = 30
    RESOLVE = 40
    CLEANUP = 50
    FINALIZE = 60

ClassContainer

Bases: ContainerInterface

A class list wrapper with an easy access api.

Parameters:

Name Type Description Default
config GeneratorConfig

The generator configuration instance

required

Attributes:

Name Type Description
processors Dict[int, List]

A step-processors mapping

data Dict[int, List]

The class qname map

step int

The current process step

Source code in xsdata/codegen/container.py
 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
285
286
287
288
289
class ClassContainer(ContainerInterface):
    """A class list wrapper with an easy access api.

    Args:
        config: The generator configuration instance

    Attributes:
        processors: A step-processors mapping
        data: The class qname map
        step: The current process step
    """

    __slots__ = ("processors", "step")

    def __init__(self, config: GeneratorConfig):
        """Initialize the container and all the class processors.

        The order of the steps and the processors is the secret
        recipe of the xsdata code generator.

        Args:
            config: The generator configuration instance
        """
        super().__init__(config)
        self.step: int = 0
        self.processors: Dict[int, List] = {
            Steps.UNGROUP: [
                FlattenAttributeGroups(self),
            ],
            Steps.FLATTEN: [
                CalculateAttributePaths(),
                FlattenClassExtensions(self),
                SanitizeEnumerationClass(self),
                UpdateAttributesEffectiveChoice(),
                UnnestInnerClasses(self),
                AddAttributeSubstitutions(self),
                ProcessAttributeTypes(self),
                MergeAttributes(),
                ProcessMixedContentClass(),
            ],
            Steps.SANITIZE: [
                ResetAttributeSequences(),
                RenameDuplicateAttributes(),
                SanitizeAttributesDefaultValue(self),
            ],
            Steps.RESOLVE: [
                ValidateAttributesOverrides(self),
            ],
            Steps.CLEANUP: [
                VacuumInnerClasses(),
            ],
            Steps.FINALIZE: [
                DetectCircularReferences(self),
                CreateCompoundFields(self),
                CreateWrapperFields(self),
                DisambiguateChoices(self),
                ResetAttributeSequenceNumbers(self),
            ],
        }

    def __iter__(self) -> Iterator[Class]:
        """Yield an iterator for the class map values."""
        for items in list(self.data.values()):
            yield from items

    def find(self, qname: str, condition: Callable = return_true) -> Optional[Class]:
        """Find class that matches the given qualified name and condition callable.

        Classes are allowed to have the same qualified name, e.g. xsd:Element
        extending xsd:ComplexType with the same name, you can provide and additional
        callback to filter the classes like the tag.

        Args:
            qname: The qualified name of the class
            condition: A user callable to filter further

        Returns:
            A class instance or None if no match found.
        """
        for row in self.data.get(qname, []):
            if condition(row):
                if row.status < self.step:
                    self.process_class(row, self.step)
                    return self.find(qname, condition)

                return row
        return None

    def find_inner(self, source: Class, qname: str) -> Class:
        """Search by qualified name for a specific inner class or fail.

        Args:
            source: The source class to search for the inner class
            qname: The qualified name of the inner class to look up

        Returns:
            The inner class instance

        Raises:
            CodeGenerationError: If the inner class is not found.
        """
        inner = ClassUtils.find_nested(source, qname)
        if inner.status < self.step:
            self.process_class(inner, self.step)

        return inner

    def first(self, qname: str) -> Class:
        """Return the first class that matches the qualified name.

        Args:
            qname: The qualified name of the class

        Returns:
            The first matching class

        Raises:
            KeyError: If no class matches the qualified name
        """
        classes = self.data.get(qname)
        if not classes:
            raise KeyError(f"Class {qname} not found")

        return classes[0]

    def process(self):
        """Run the processor and filter steps."""
        self.validate_classes()
        self.process_classes(Steps.UNGROUP)
        self.remove_groups()
        self.process_classes(Steps.FLATTEN)
        self.filter_classes()
        self.process_classes(Steps.SANITIZE)
        self.process_classes(Steps.RESOLVE)
        self.process_classes(Steps.CLEANUP)
        self.process_classes(Steps.FINALIZE)
        self.designate_classes()

    def validate_classes(self):
        """Merge redefined classes."""
        with stopwatch("ClassValidator"):
            ClassValidator(self).process()

    def process_classes(self, step: int):
        """Run the given step processors for all classes.

        Args:
            step: The step reference number
        """
        self.step = step
        for obj in self:
            if obj.status < step:
                self.process_class(obj, step)

    def process_class(self, target: Class, step: int):
        """Run the step processors for the given class.

        Process recursively any inner classes as well.

        Args:
            target: The target class to process
            step: The step reference number
        """
        target.status = Status(step)
        for processor in self.processors.get(step, []):
            with stopwatch(processor.__class__.__name__):
                processor.process(target)

        for inner in target.inner:
            if inner.status < step:
                self.process_class(inner, step)

        target.status = Status(step + 1)

    def designate_classes(self):
        """Designate the final class names, packages and modules."""
        designators = [
            RenameDuplicateClasses(self),
            ValidateReferences(self),
            DesignateClassPackages(self),
        ]

        for designator in designators:
            with stopwatch(designator.__class__.__name__):
                designator.run()

    def filter_classes(self):
        """Filter the classes to be generated."""
        with stopwatch(FilterClasses.__name__):
            FilterClasses(self).run()

    def remove_groups(self):
        """Remove xs:groups and xs:attributeGroups from the container."""
        self.set([x for x in iter(self) if not x.is_group])

    def add(self, item: Class):
        """Add class item to the container.

        Args:
            item: The class instance to add
        """
        self.data.setdefault(item.qname, []).append(item)

    def remove(self, *items: Class):
        """Safely remove classes from the container.

        Args:
            items: The classes to remove
        """
        for item in items:
            self.data[item.qname] = [
                c for c in self.data[item.qname] if c.ref != item.ref
            ]

    def reset(self, item: Class, qname: str):
        """Update the given class qualified name.

        Args:
            item: The target class instance to update
            qname: The new qualified name of the class
        """
        self.data[qname] = [c for c in self.data[qname] if c.ref != item.ref]
        self.add(item)

    def set(self, items: List[Class]):
        """Set the list of classes to the container.

        Args:
            items: The list of classes
        """
        self.data.clear()
        self.extend(items)

    def extend(self, items: List[Class]):
        """Add a list of classes to the container.

        Args:
            items: The list of class instances to add
        """
        collections.apply(items, self.add)

__init__(config)

Initialize the container and all the class processors.

The order of the steps and the processors is the secret recipe of the xsdata code generator.

Parameters:

Name Type Description Default
config GeneratorConfig

The generator configuration instance

required
Source code in xsdata/codegen/container.py
 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
def __init__(self, config: GeneratorConfig):
    """Initialize the container and all the class processors.

    The order of the steps and the processors is the secret
    recipe of the xsdata code generator.

    Args:
        config: The generator configuration instance
    """
    super().__init__(config)
    self.step: int = 0
    self.processors: Dict[int, List] = {
        Steps.UNGROUP: [
            FlattenAttributeGroups(self),
        ],
        Steps.FLATTEN: [
            CalculateAttributePaths(),
            FlattenClassExtensions(self),
            SanitizeEnumerationClass(self),
            UpdateAttributesEffectiveChoice(),
            UnnestInnerClasses(self),
            AddAttributeSubstitutions(self),
            ProcessAttributeTypes(self),
            MergeAttributes(),
            ProcessMixedContentClass(),
        ],
        Steps.SANITIZE: [
            ResetAttributeSequences(),
            RenameDuplicateAttributes(),
            SanitizeAttributesDefaultValue(self),
        ],
        Steps.RESOLVE: [
            ValidateAttributesOverrides(self),
        ],
        Steps.CLEANUP: [
            VacuumInnerClasses(),
        ],
        Steps.FINALIZE: [
            DetectCircularReferences(self),
            CreateCompoundFields(self),
            CreateWrapperFields(self),
            DisambiguateChoices(self),
            ResetAttributeSequenceNumbers(self),
        ],
    }

__iter__()

Yield an iterator for the class map values.

Source code in xsdata/codegen/container.py
110
111
112
113
def __iter__(self) -> Iterator[Class]:
    """Yield an iterator for the class map values."""
    for items in list(self.data.values()):
        yield from items

find(qname, condition=return_true)

Find class that matches the given qualified name and condition callable.

Classes are allowed to have the same qualified name, e.g. xsd:Element extending xsd:ComplexType with the same name, you can provide and additional callback to filter the classes like the tag.

Parameters:

Name Type Description Default
qname str

The qualified name of the class

required
condition Callable

A user callable to filter further

return_true

Returns:

Type Description
Optional[Class]

A class instance or None if no match found.

Source code in xsdata/codegen/container.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def find(self, qname: str, condition: Callable = return_true) -> Optional[Class]:
    """Find class that matches the given qualified name and condition callable.

    Classes are allowed to have the same qualified name, e.g. xsd:Element
    extending xsd:ComplexType with the same name, you can provide and additional
    callback to filter the classes like the tag.

    Args:
        qname: The qualified name of the class
        condition: A user callable to filter further

    Returns:
        A class instance or None if no match found.
    """
    for row in self.data.get(qname, []):
        if condition(row):
            if row.status < self.step:
                self.process_class(row, self.step)
                return self.find(qname, condition)

            return row
    return None

find_inner(source, qname)

Search by qualified name for a specific inner class or fail.

Parameters:

Name Type Description Default
source Class

The source class to search for the inner class

required
qname str

The qualified name of the inner class to look up

required

Returns:

Type Description
Class

The inner class instance

Raises:

Type Description
CodeGenerationError

If the inner class is not found.

Source code in xsdata/codegen/container.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def find_inner(self, source: Class, qname: str) -> Class:
    """Search by qualified name for a specific inner class or fail.

    Args:
        source: The source class to search for the inner class
        qname: The qualified name of the inner class to look up

    Returns:
        The inner class instance

    Raises:
        CodeGenerationError: If the inner class is not found.
    """
    inner = ClassUtils.find_nested(source, qname)
    if inner.status < self.step:
        self.process_class(inner, self.step)

    return inner

first(qname)

Return the first class that matches the qualified name.

Parameters:

Name Type Description Default
qname str

The qualified name of the class

required

Returns:

Type Description
Class

The first matching class

Raises:

Type Description
KeyError

If no class matches the qualified name

Source code in xsdata/codegen/container.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def first(self, qname: str) -> Class:
    """Return the first class that matches the qualified name.

    Args:
        qname: The qualified name of the class

    Returns:
        The first matching class

    Raises:
        KeyError: If no class matches the qualified name
    """
    classes = self.data.get(qname)
    if not classes:
        raise KeyError(f"Class {qname} not found")

    return classes[0]

process()

Run the processor and filter steps.

Source code in xsdata/codegen/container.py
175
176
177
178
179
180
181
182
183
184
185
186
def process(self):
    """Run the processor and filter steps."""
    self.validate_classes()
    self.process_classes(Steps.UNGROUP)
    self.remove_groups()
    self.process_classes(Steps.FLATTEN)
    self.filter_classes()
    self.process_classes(Steps.SANITIZE)
    self.process_classes(Steps.RESOLVE)
    self.process_classes(Steps.CLEANUP)
    self.process_classes(Steps.FINALIZE)
    self.designate_classes()

validate_classes()

Merge redefined classes.

Source code in xsdata/codegen/container.py
188
189
190
191
def validate_classes(self):
    """Merge redefined classes."""
    with stopwatch("ClassValidator"):
        ClassValidator(self).process()

process_classes(step)

Run the given step processors for all classes.

Parameters:

Name Type Description Default
step int

The step reference number

required
Source code in xsdata/codegen/container.py
193
194
195
196
197
198
199
200
201
202
def process_classes(self, step: int):
    """Run the given step processors for all classes.

    Args:
        step: The step reference number
    """
    self.step = step
    for obj in self:
        if obj.status < step:
            self.process_class(obj, step)

process_class(target, step)

Run the step processors for the given class.

Process recursively any inner classes as well.

Parameters:

Name Type Description Default
target Class

The target class to process

required
step int

The step reference number

required
Source code in xsdata/codegen/container.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def process_class(self, target: Class, step: int):
    """Run the step processors for the given class.

    Process recursively any inner classes as well.

    Args:
        target: The target class to process
        step: The step reference number
    """
    target.status = Status(step)
    for processor in self.processors.get(step, []):
        with stopwatch(processor.__class__.__name__):
            processor.process(target)

    for inner in target.inner:
        if inner.status < step:
            self.process_class(inner, step)

    target.status = Status(step + 1)

designate_classes()

Designate the final class names, packages and modules.

Source code in xsdata/codegen/container.py
224
225
226
227
228
229
230
231
232
233
234
def designate_classes(self):
    """Designate the final class names, packages and modules."""
    designators = [
        RenameDuplicateClasses(self),
        ValidateReferences(self),
        DesignateClassPackages(self),
    ]

    for designator in designators:
        with stopwatch(designator.__class__.__name__):
            designator.run()

filter_classes()

Filter the classes to be generated.

Source code in xsdata/codegen/container.py
236
237
238
239
def filter_classes(self):
    """Filter the classes to be generated."""
    with stopwatch(FilterClasses.__name__):
        FilterClasses(self).run()

remove_groups()

Remove xs:groups and xs:attributeGroups from the container.

Source code in xsdata/codegen/container.py
241
242
243
def remove_groups(self):
    """Remove xs:groups and xs:attributeGroups from the container."""
    self.set([x for x in iter(self) if not x.is_group])

add(item)

Add class item to the container.

Parameters:

Name Type Description Default
item Class

The class instance to add

required
Source code in xsdata/codegen/container.py
245
246
247
248
249
250
251
def add(self, item: Class):
    """Add class item to the container.

    Args:
        item: The class instance to add
    """
    self.data.setdefault(item.qname, []).append(item)

remove(*items)

Safely remove classes from the container.

Parameters:

Name Type Description Default
items Class

The classes to remove

()
Source code in xsdata/codegen/container.py
253
254
255
256
257
258
259
260
261
262
def remove(self, *items: Class):
    """Safely remove classes from the container.

    Args:
        items: The classes to remove
    """
    for item in items:
        self.data[item.qname] = [
            c for c in self.data[item.qname] if c.ref != item.ref
        ]

reset(item, qname)

Update the given class qualified name.

Parameters:

Name Type Description Default
item Class

The target class instance to update

required
qname str

The new qualified name of the class

required
Source code in xsdata/codegen/container.py
264
265
266
267
268
269
270
271
272
def reset(self, item: Class, qname: str):
    """Update the given class qualified name.

    Args:
        item: The target class instance to update
        qname: The new qualified name of the class
    """
    self.data[qname] = [c for c in self.data[qname] if c.ref != item.ref]
    self.add(item)

set(items)

Set the list of classes to the container.

Parameters:

Name Type Description Default
items List[Class]

The list of classes

required
Source code in xsdata/codegen/container.py
274
275
276
277
278
279
280
281
def set(self, items: List[Class]):
    """Set the list of classes to the container.

    Args:
        items: The list of classes
    """
    self.data.clear()
    self.extend(items)

extend(items)

Add a list of classes to the container.

Parameters:

Name Type Description Default
items List[Class]

The list of class instances to add

required
Source code in xsdata/codegen/container.py
283
284
285
286
287
288
289
def extend(self, items: List[Class]):
    """Add a list of classes to the container.

    Args:
        items: The list of class instances to add
    """
    collections.apply(items, self.add)