Skip to content

container

xsdata.codegen.container

Steps

Process steps.

Source code in xsdata/codegen/container.py
33
34
35
36
37
38
39
40
class Steps:
    """Process steps."""

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

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

step int

The current process step

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

    Args:
        config: The generator configuration instance

    Attributes:
        processors: A step-processors mapping
        step: The current process step
    """

    __slots__ = ("data", "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.data: Dict = {}

        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.FINALIZE: [
                VacuumInnerClasses(),
                CreateCompoundFields(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_inner(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.

        Steps:
            1. Ungroup xs:groups and xs:attributeGroups
            2. Remove the group classes from the container
            3. Flatten extensions, attrs and attr types
            4. Remove the classes that won't be generated
            5. Resolve attrs overrides
            5. Create compound fields, cleanup classes and atts
            7. Designate final class names, packages and modules
        """
        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.FINALIZE)
        self.designate_classes()

    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, []):
            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),
            DesignateClassPackages(self),
        ]

        for designator in designators:
            designator.run()

    def filter_classes(self):
        """Filter the classes to be generated."""
        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 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].remove(item)
        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
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
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.data: Dict = {}

    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.FINALIZE: [
            VacuumInnerClasses(),
            CreateCompoundFields(self),
            ResetAttributeSequenceNumbers(self),
        ],
    }

__iter__()

Yield an iterator for the class map values.

Source code in xsdata/codegen/container.py
100
101
102
103
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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_inner(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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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.

Steps
  1. Ungroup xs:groups and xs:attributeGroups
  2. Remove the group classes from the container
  3. Flatten extensions, attrs and attr types
  4. Remove the classes that won't be generated
  5. Resolve attrs overrides
  6. Create compound fields, cleanup classes and atts
  7. Designate final class names, packages and modules
Source code in xsdata/codegen/container.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def process(self):
    """Run the processor and filter steps.

    Steps:
        1. Ungroup xs:groups and xs:attributeGroups
        2. Remove the group classes from the container
        3. Flatten extensions, attrs and attr types
        4. Remove the classes that won't be generated
        5. Resolve attrs overrides
        5. Create compound fields, cleanup classes and atts
        7. Designate final class names, packages and modules
    """
    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.FINALIZE)
    self.designate_classes()

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
186
187
188
189
190
191
192
193
194
195
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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, []):
        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
216
217
218
219
220
221
222
223
224
def designate_classes(self):
    """Designate the final class names, packages and modules."""
    designators = [
        RenameDuplicateClasses(self),
        DesignateClassPackages(self),
    ]

    for designator in designators:
        designator.run()

filter_classes()

Filter the classes to be generated.

Source code in xsdata/codegen/container.py
226
227
228
def filter_classes(self):
    """Filter the classes to be generated."""
    FilterClasses(self).run()

remove_groups()

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

Source code in xsdata/codegen/container.py
230
231
232
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
234
235
236
237
238
239
240
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)

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
242
243
244
245
246
247
248
249
250
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].remove(item)
    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
252
253
254
255
256
257
258
259
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
261
262
263
264
265
266
267
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)