cattrs
cattrs copied to clipboard
Syntax Error in generated code
- cattrs version: current master
- Python version: 3.10
- Operating System: Linux
The error
File ".venv/lib/python3.10/site-packages/cattrs/dispatch.py", line 122, in dispatch
return handler(typ)
File ".venv/lib/python3.10/site-packages/cattrs/converters.py", line 829, in gen_structure_mapping
h = make_mapping_structure_fn(
File ".venv/lib/python3.10/site-packages/cattrs/gen.py", line 726, in make_mapping_structure_fn
eval(compile(script, "", "exec"), globs)
File "<string>", line 17
raise IterableValidationError('While structuring dict[typing.Union[typing.Literal['ca', 'pro', 'fa', 'car', 'ing_emb'], typing.Literal['wgr', 'cwg', 'fcc', 'wcc']], statistics.FrequenciesInfo]', errors, __cattr_mapping_cl)
| SyntaxError: invalid syntax. Perhaps you forgot a comma?
The offending code is here gen :

It seems to generate code that assumes that the repr of the offending type does not include '. ' is not escaped.
Thanks, I'm aware of this (there's another, similar issue), it's on my radar for the next version. Just out of curiosity, if you change the line to
raise IterableValidatoinError("While structuring {cl!r}", errors, __cattr_mapping_cl)
i.e. single quotes to double quotes, does it fix it?
Yes, that does seem to fix it. Though I'm not sure if I would trust all types to not contain a " either.
Yeah, the play might be to just escape any single quotes in the repr.
@phiresky this should be fixed on main, can you verify before I release the next version?
Thanks for fixing it! Sorry, it might take a while before I get back to the code that for me generates this error, so probably you shouldn't wait for me.
Seems to work, though I'm getting a .venv/lib/python3.10/site-packages/cattrs/converters.py:541: error: Invalid "type: ignore" comment mypy error on master
Confirmed. Will test on 3.7 too before removing the comment.
I fixed it by removing the comment, seems to work fine. Give it one more test for me? <3
I'm I thought that mypy also accept # type: ignore syntax 🤔
It does. It can be configured to not take it though, which I think is happening (at least for me, I have that option set up).
got it. I think I also configure it to accept the syntax on pyright end. Removing it makes sense then.