SelectMultiple widget value_from_datadict enhancement suggestion

81 views
Skip to first unread message

Marcin Nowak

unread,
Jul 16, 2016, 4:41:59 PM7/16/16
to Django developers (Contributions to Django itself)
Dear all.

I would just say that implementation of SelectMultiple.value_from_datadict is not based on duck typing, and has some disadvantages.

    def value_from_datadict(self, data, files, name):
        if isinstance(data, MultiValueDict):
            return data.getlist(name)
        return data.get(name)

First, always checking the instance type has worse efficiency than try-except block, because most hits may be returned without any additional checking.
Second, as an author of library which also works with Django, I'm providing multivalue-like dict, but own implemented - it is not an instance of MultiValueDict and never be, but it has similar interface (i.e. `get()` and `getlist()` methods) 

Duck typing will work for both cases. The implementation might look like:

    def value_from_datadict(self, data, files, name):
        try:        
            return data.getlist(name)
        except AttributeError:        
            return data.get(name)

For most cases a MultiValueDict / QueryDict are passed to forms, so the function will immediately return a proper value, and will also work for objects that "looks like MultiValueDict". On other cases it assumes that the `data` object is dict-like.

What do you think?

Kind Regards,
Marcin

Tim Graham

unread,
Jul 16, 2016, 8:56:45 PM7/16/16
to Django developers (Contributions to Django itself)
I've seen a few patches recently to move things toward duck-typing so this seems welcome.
Reply all
Reply to author
Forward
0 new messages