Skip to content

Commit f38f818

Browse files
authored
Merge pull request #17516 from github/redsun82/codegen-annotate
Codegen: allow to attach docstrings after the definition
2 parents 682f08c + c117a53 commit f38f818

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

misc/codegen/lib/schemadefs.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,3 +177,19 @@ def group(name: str = "") -> _ClassDecorator:
177177
from_class=_schema.get_type_name(ref)))
178178
synth.on_arguments = lambda **kwargs: _annotate(
179179
synth=_schema.SynthInfo(on_arguments={k: _schema.get_type_name(t) for k, t in kwargs.items()}))
180+
181+
182+
def annotate(annotated_cls: type) -> _Callable[[type], None]:
183+
"""
184+
Add or modify schema annotations after a class has been defined
185+
For the moment, only docstring annotation is supported. In the future, any kind of
186+
modification will be allowed.
187+
188+
The name of the class used for annotation must be `_`
189+
"""
190+
def decorator(cls: type) -> None:
191+
if cls.__name__ != "_":
192+
raise _schema.Error("Annotation classes must be named _")
193+
annotated_cls.__doc__ = cls.__doc__
194+
return None
195+
return decorator

misc/codegen/loaders/schemaloader.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ def load(m: types.ModuleType) -> schema.Schema:
138138
if name == "__includes":
139139
includes = data
140140
continue
141-
if name.startswith("__"):
141+
if name.startswith("__") or name == "_":
142142
continue
143143
cls = _get_class(data)
144144
if classes and not cls.bases:

misc/codegen/test/test_schemaloader.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -756,6 +756,39 @@ class D(Root):
756756
}
757757

758758

759+
def test_annotate_docstring():
760+
@load
761+
class data:
762+
class Root:
763+
""" old docstring """
764+
765+
@defs.annotate(Root)
766+
class _:
767+
"""
768+
new
769+
docstring
770+
"""
771+
772+
assert data.classes == {
773+
"Root": schema.Class("Root", doc=["new", "docstring"]),
774+
}
775+
776+
777+
def test_annotate_not_underscore():
778+
with pytest.raises(schema.Error):
779+
@load
780+
class data:
781+
class Root:
782+
pass
783+
784+
@defs.annotate(Root)
785+
class Something:
786+
"""
787+
new
788+
docstring
789+
"""
790+
791+
759792
def test_test_with_unknown_string():
760793
with pytest.raises(schema.Error):
761794
@load

0 commit comments

Comments
 (0)