[Django] #35723: formset all_valid use generator comprehension instead of list comprehension

4 views
Skip to first unread message

Django

unread,
Aug 31, 2024, 12:19:36 AM8/31/24
to django-...@googlegroups.com
#35723: formset all_valid use generator comprehension instead of list comprehension
-------------------------------------+-------------------------------------
Reporter: sahasrara62 | Type:
| Cleanup/optimization
Status: new | Component: Forms
Version: dev | Severity: Normal
Keywords: formsets, | Triage Stage:
validation | Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 1 | UI/UX: 0
-------------------------------------+-------------------------------------
in function `all_valid` in `formsets.py`
https://github.com/django/django/blob/main/django/forms/formsets.py#L576
we are using list comprehension to check if each individual formset is
valid or not and then adding that to list and then computing all. in this
approach, we have to go through all the formsets even if one of them is
not valid and then check if all of them are true.

with this approach, we have to check all formsets first and then check if
all of list is valid ie True. An extra computation is happening even
after if encounter not valid and in memory is also used .

my purposal is to use generator comprehension here instead of list
comprehension.
benefits include, no need to validate all formset if one of formset is
invalid and less in memory usages.

so code should look like

from
{{{
def all_valid(formsets):
"""Validate every formset and return True if all are valid."""
# List comprehension ensures is_valid() is called for all formsets.
return all([formset.is_valid() for formset in formsets])
}}}
to


{{{
def all_valid(formsets):
"""Validate every formset and return True if all are valid."""
return all(formset.is_valid() for formset in formsets)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/35723>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
Reply all
Reply to author
Forward
0 new messages