Proposal: Add utility class "ClassList"

75 views
Skip to first unread message

Jacob Rief

unread,
Sep 23, 2022, 5:14:27 AM9/23/22
to Django developers (Contributions to Django itself)
In JavaScript each HTMLElement has a property named classList
This actually is a set allowing to add a single CSS class string, remove it
and/or toggle it.

If we would reimplement this as a Python class, methods such as
css_classes could be implemented as a one-liner. This would also be beneficial
for future uses of similar methods in Django and 3rd party libraries, because it is a quite
common use case that one has to change the list of CSS classes as an element
attribute.

– Jacob

Carlton Gibson

unread,
Sep 29, 2022, 4:35:02 AM9/29/22
to Django developers (Contributions to Django itself)
Hey Jacob. Thanks for this. 

Can I ask you to give a few examples of potential usages in Django, and showing the gain over use a set in these cases? 

I'm trying to imagine exactly what you have in mind, but I'm not entirely clear. 

Thanks again. 
Carlton

Jacob Rief

unread,
Sep 30, 2022, 3:43:02 AM9/30/22
to Django developers (Contributions to Django itself)
Hey Carlton,
in my opinion, the main use case would be to improve type safety, readability and to add a
utility class for 3rd party packages. Someday, Django may add type hints and then this would
be really beneficial.

In Django itself, the mentioned method css_classes does not offer any type safety;
the passed in argument extra_classes can be None, a string containing a single
CSS class or list containing those classes.

By adding such a utility class, we can rewrite the above method to

css_classes(extra_classes: ClassList):
    # optionally: extra_classes = ClassList(extra_classes)
    extra_classes.toggle(getattr(self.form, "error_css_class", None), self.errors)
    extra_classes.toggle(getattr(self.form, "required_css_class", None), self.field.required)
    return extra_classes

which is much easier to read.

In my project django-formset, I was able to remove a lot of boilerplate, by introducing that class.

Naming that Python class ClassSet or CSSClassSet or CSSClasses might be a better option.
I used ClassList because that's the name in JavaScript.

– Jacob  
Reply all
Reply to author
Forward
0 new messages