Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SyntaxError generating TypedDict structure function #376

Closed
simonschmidt opened this issue Jun 6, 2023 · 3 comments
Closed

SyntaxError generating TypedDict structure function #376

simonschmidt opened this issue Jun 6, 2023 · 3 comments
Labels
Milestone

Comments

@simonschmidt
Copy link

Since 23.1 creating a converter for TypedDict can lead to SyntaxError in the generated function if the TypedDict fields are not valid identifiers.

For example here's a TypedDict with a field containing .

from typing import TypedDict
import cattrs

converter = cattrs.Converter()

TD = TypedDict(
    "TD",
    {"x.y": int},

)

print(
    converter.structure(
        {"x.y": "3"},
        TD,
    )
)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/app/cattrs/src/repro.py", line 13, in <module>
    converter.structure(
  File "/app/cattrs/src/cattrs/converters.py", line 334, in structure
    return self._structure_func.dispatch(cl)(obj, cl)
  File "/app/cattrs/src/cattrs/dispatch.py", line 48, in _dispatch
    res = self._function_dispatch.dispatch(typ)
  File "/app/cattrs/src/cattrs/dispatch.py", line 133, in dispatch
    return handler(typ)
  File "/app/cattrs/src/cattrs/converters.py", line 973, in gen_structure_typeddict
    return make_typeddict_dict_struct_fn(
  File "/app/cattrs/src/cattrs/gen/typeddicts.py", line 513, in make_dict_structure_fn
    eval(compile(script, fname, "exec"), globs)
  File "<cattrs generated structure repro.TD>", line 1
    def structure_TD(o, _, *, __cl=__cl, __c_cve=__c_cve, __c_avn=__c_avn, __c_structure_x.y=__c_structure_x.y, __c_type_x.y=__c_type_x.y, __c_structure_a=__c_structure_a, __c_type_a=__c_type_a):
    
SyntaxError: invalid syntax

The issue seems to be in how struct_handler_name and type_name are created in https://github.com/python-attrs/cattrs/blob/main/src/cattrs/gen/typeddicts.py#L241

Though I don't know the details here well enough to know if it'd be sufficient to sanitize those variables or if there's more going on here.

@Tinche Tinche added the bug label Jun 6, 2023
@Tinche
Copy link
Member

Tinche commented Jun 6, 2023

Ooph ok, thanks for reporting. We'll need to figure something out, yeah.

@Tinche Tinche added this to the 23.2 milestone Jun 6, 2023
@Tinche
Copy link
Member

Tinche commented Jun 7, 2023

Hi, I think this is fixed on main, can you verify for your use case?

@simonschmidt
Copy link
Author

It's fixed, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants