@@ -137,9 +137,10 @@ class Option(enum.Flag):
137137_SCHEMA_CLASSES = []
138138
139139
140- def register_schema (cls ):
140+ def register_schema (cls : type | None = None , * , priority : int = 0 ):
141141 """
142142 Decorator to register a class as a known ``Schema``
143+ It also accept a priority value to sort the list of schemas. Default schemas have priority 0.
143144
144145 Schema classes are instantiated when calling ``schema``. Example use::
145146
@@ -149,10 +150,15 @@ class MySchema(Schema):
149150 def handles_type(cls, py_type: Type) -> bool:
150151 ...
151152 ...
152-
153153 """
154- _SCHEMA_CLASSES .append (cls )
155- return cls
154+
155+ def _wrapper (_cls ):
156+ """Wrapper function to attach priority and sort the list of schemas."""
157+ _cls .__py_avro_priority = priority
158+ _SCHEMA_CLASSES .append (_cls )
159+ return _cls
160+
161+ return _wrapper if not cls else _wrapper (cls )
156162
157163
158164def schema (
@@ -188,7 +194,7 @@ def _schema_obj(py_type: Type, namespace: Optional[str] = None, options: Option
188194 :param options: Schema generation options.
189195 """
190196 # Find concrete Schema subclasses defined in the current module
191- for schema_class in _SCHEMA_CLASSES :
197+ for schema_class in sorted ( _SCHEMA_CLASSES , key = lambda c : getattr ( c , "__py_avro_priority" , 0 )) :
192198 # Find the first schema class that handles py_type
193199 schema_obj = schema_class (py_type , namespace = namespace , options = options ) # type: ignore
194200 if schema_obj :
0 commit comments