sander76 / clipstick

create cli applications using pydantic models
https://sander76.github.io/clipstick/
MIT License
27 stars 3 forks source link

fix: support non-toplevel models #59

Closed airwoodix closed 7 months ago

airwoodix commented 7 months ago

Parsing the AST of a model not defined in a module top-level fails with an indentation error. With the new test in this patch:

src/clipstick/_docstring.py:10: in set_undefined_field_descriptions_from_var_docstrings
    module = ast.parse(inspect.getsource(model))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

source = '    class ModelInClass(BaseModel):\n        my_value_docstring: str\n        """Docstring for my_value."""\n\n        my_value_annotation: str = Field(description="Description for my_value.")\n'
filename = '<unknown>', mode = 'exec'

    def parse(source, filename='<unknown>', mode='exec', *,
              type_comments=False, feature_version=None):
        """
        Parse the source into an AST node.
        Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
        Pass type_comments=True to get back type comments where the syntax allows.
        """
        flags = PyCF_ONLY_AST
        if type_comments:
            flags |= PyCF_TYPE_COMMENTS
        if isinstance(feature_version, tuple):
            major, minor = feature_version  # Should be a 2-tuple.
            assert major == 3
            feature_version = minor
        elif feature_version is None:
            feature_version = -1
        # Else it should be an int giving the minor version for 3.x.
>       return compile(source, filename, mode, flags,
                       _feature_version=feature_version)
E         File "<unknown>", line 1
E           class ModelInClass(BaseModel):
E       IndentationError: unexpected indent

.../python3.11/ast.py:50: IndentationError

The patch uses textwrap.dedent on the model source before passing it to the AST parser.

sander76 commented 7 months ago

Thanks for this pr ! I pointed your pr to my dev branch (need to update my docs on this). Will release shortly!

airwoodix commented 7 months ago

Thanks for the quick review and release!