Skip to content

Commit

Permalink
Handle TypeError in TypeConversionDict
Browse files Browse the repository at this point in the history
TypeErrors are now handled in the same manner as ValueErrors.

fixes #2842
  • Loading branch information
Sympatron authored and pgjones committed Mar 3, 2024
1 parent 4c09d1b commit f516c40
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ Version 3.0.2

Unreleased

- Fix handling of TypeError in TypeConversionDict.get() to match
ValueErrors. :issue:`2843`
- Fix response_wrapper type check in test client. :issue:`2831`
- Make the return type of ``MultiPartParser.parse`` more
precise. :issue:`2840`
Expand Down
10 changes: 7 additions & 3 deletions src/werkzeug/datastructures/structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,12 @@ def get(self, key, default=None, type=None):
be looked up. If not further specified `None` is
returned.
:param type: A callable that is used to cast the value in the
:class:`MultiDict`. If a :exc:`ValueError` is raised
by this callable the default value is returned.
:class:`MultiDict`. If a :exc:`ValueError` or a
:exc:`TypeError` is raised by this callable the default
value is returned.
.. versionchanged:: 3.0.2
Returns the default value on :exc:`TypeError`, too.
"""
try:
rv = self[key]
Expand All @@ -80,7 +84,7 @@ def get(self, key, default=None, type=None):
if type is not None:
try:
rv = type(rv)
except ValueError:
except (ValueError, TypeError):
rv = default
return rv

Expand Down
3 changes: 2 additions & 1 deletion tests/test_datastructures.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,8 +550,9 @@ def test_value_conversion(self):
assert d.get("foo", type=int) == 1

def test_return_default_when_conversion_is_not_possible(self):
d = self.storage_class(foo="bar")
d = self.storage_class(foo="bar", baz=None)
assert d.get("foo", default=-1, type=int) == -1
assert d.get("baz", default=-1, type=int) == -1

def test_propagate_exceptions_in_conversion(self):
d = self.storage_class(foo="bar")
Expand Down

0 comments on commit f516c40

Please sign in to comment.