mirror of
https://github.com/django/django.git
synced 2025-10-31 09:41:08 +00:00
Refs #36383 -- Extended DeconstructibleSerializer to support non-identifier keyword arguments.
In Python, keyword arguments must normally be valid identifiers (i.e., variable names that follow Python's naming rules). However, Python dicts can have keys that aren't valid identifiers, like "foo-bar" or "123foo". This commit ensures that keyword arguments that are nt valid identifiers, are properly handled when deconstructing an object.
This commit is contained in:
@@ -102,10 +102,20 @@ class DeconstructibleSerializer(BaseSerializer):
|
||||
arg_string, arg_imports = serializer_factory(arg).serialize()
|
||||
strings.append(arg_string)
|
||||
imports.update(arg_imports)
|
||||
non_ident_kwargs = {}
|
||||
for kw, arg in sorted(kwargs.items()):
|
||||
arg_string, arg_imports = serializer_factory(arg).serialize()
|
||||
imports.update(arg_imports)
|
||||
strings.append("%s=%s" % (kw, arg_string))
|
||||
if kw.isidentifier():
|
||||
arg_string, arg_imports = serializer_factory(arg).serialize()
|
||||
imports.update(arg_imports)
|
||||
strings.append("%s=%s" % (kw, arg_string))
|
||||
else:
|
||||
non_ident_kwargs[kw] = arg
|
||||
if non_ident_kwargs:
|
||||
# Serialize non-identifier keyword arguments as a dict.
|
||||
kw_string, kw_imports = serializer_factory(non_ident_kwargs).serialize()
|
||||
strings.append(f"**{kw_string}")
|
||||
imports.update(kw_imports)
|
||||
|
||||
return "%s(%s)" % (name, ", ".join(strings)), imports
|
||||
|
||||
@staticmethod
|
||||
|
||||
Reference in New Issue
Block a user