|
| 1 | +import modelspec |
| 2 | +from modelspec import field, instance_of, optional |
| 3 | +from modelspec.base_types import Base |
| 4 | +from typing import List |
| 5 | + |
| 6 | +# Example testing multiple options... |
| 7 | + |
| 8 | +from typing import Any |
| 9 | + |
| 10 | + |
| 11 | +def convert2float(x: Any) -> float: |
| 12 | + print("Converting {} ({})".format(x, type(x))) |
| 13 | + """Convert to float if not None""" |
| 14 | + if x is not None: |
| 15 | + return float(x) |
| 16 | + else: |
| 17 | + return None |
| 18 | + |
| 19 | + |
| 20 | +@modelspec.define |
| 21 | +class TopClass(Base): |
| 22 | + """ |
| 23 | + A model.... |
| 24 | +
|
| 25 | + Args: |
| 26 | + id: The unique id of the thing |
| 27 | + float_like_req: name says it all... |
| 28 | + float_like_optional: name also says it all... |
| 29 | + """ |
| 30 | + |
| 31 | + id: str = field(validator=instance_of(str)) |
| 32 | + float_like_req: int = field( |
| 33 | + default=None, validator=instance_of(float), converter=convert2float |
| 34 | + ) |
| 35 | + float_like_optional: int = field( |
| 36 | + default=None, validator=optional(instance_of(float)), converter=convert2float |
| 37 | + ) |
| 38 | + |
| 39 | + |
| 40 | +tc = TopClass( |
| 41 | + id="MyTest", float_like_req="03" |
| 42 | +) # a string which can be converted to a float... |
| 43 | + |
| 44 | +# tc.float_like_req = 2.01 |
| 45 | +tc.float_like_optional = 43 |
| 46 | + |
| 47 | + |
| 48 | +print(tc) |
| 49 | + |
| 50 | +tc.to_yaml_file("test_instance.yaml") |
| 51 | + |
| 52 | +doc_md = tc.generate_documentation(format="markdown") |
| 53 | + |
| 54 | +with open("test.md", "w") as d: |
| 55 | + d.write(doc_md) |
| 56 | + |
| 57 | + |
| 58 | +print("\nGenerating specification in dict form") |
| 59 | +doc_dict = tc.generate_documentation(format="dict") |
| 60 | + |
| 61 | +import yaml |
| 62 | + |
| 63 | +print("Generating specification in YAML") |
| 64 | +with open("test.specification.yaml", "w") as d: |
| 65 | + d.write(yaml.dump(doc_dict, indent=4, sort_keys=False)) |
0 commit comments