werkzeug icon indicating copy to clipboard operation
werkzeug copied to clipboard

`TypeConversionDict.pop` could pop with type

Open lczyk opened this issue 1 year ago • 1 comments

TypeConversionDict provides a type argument for the get method, but does not do the same for pop. Currently this is the way to do a typed pop:

d = TypeConversionDict(foo='99', bar='baz')
v = d.get('foo', type=int)
if v is not None:
     d.pop('foo')
reveal_type(v)  # int | None

I propose:

d = TypeConversionDict(foo='99', bar='baz')
v = d.pop('foo', type=int)  # currently this does not work
reveal_type(v)  # int | None

Implementation suggestion:

  def pop(self, key, default=_missing, type=None):
      value = self.get(key, default, type)
      if value is _missing:
          raise KeyError(key)
      del self[key]
      return value

I'm using _missing to correct reproduce the behaviour of pop, and re-using self.get sice we don't want the item to be pop-ed if the type-conversion fails (yes??. i guess that's the tricky bit, no?)

lczyk avatar Apr 23 '24 12:04 lczyk

I'm taking the change of title from a question to a statement as a tentative approval of the idea. Hence, see PR for code. The actual implementation ended up being a bit more messy than proposed but its roughly the same idea.

lczyk avatar Apr 26 '24 16:04 lczyk