why KeyError when Get doesn't find a key?

223 views
Skip to first unread message

Michael Wang-Helmke

unread,
Dec 4, 2012, 2:26:00 PM12/4/12
to py-le...@googlegroups.com
Hi,

I'm bugged that the semantics for the Get function are to "fail" with an exception if Get doesn't find a key.  I strongly feel exceptions should be for legitimate failures and errors.  I don't see a missing key being an error condition.  A common use case for me is to test if a key is present by trying to Get it.

I would much prefer that Get return None when there is no key present.  I have modified my local copy to have this behavior.

Does anyone see any issues with this?

Thank you,

Michael

Árni Már Jónsson

unread,
Dec 4, 2012, 4:19:06 PM12/4/12
to py-le...@googlegroups.com
Hi,

I don´t really remember why I chose those semantics, but I imagine it was to mimic the semantics of the builtin Python type dict.

Changing the semantics this late in the game is not an option I think, but I´d be very happy to add a "default" keyword argument, which is returned when Get() doesn´t find its value. 

Perhaps there´s a simpler backwards-compatible way to achieve the same thing?

Regards, Árni Már

Michael Wang-Helmke

unread,
Dec 10, 2012, 6:31:48 PM12/10/12
to py-le...@googlegroups.com
Hi,

The default argument is a good idea.  I would just pass in "None" as a default.  In the mean time, I modified my version of the source and it works nicely for me.  Thank you for writing the python bindings for this, it has been very helpful.

Thank you,

Michael

Árni Már Jónsson

unread,
Dec 21, 2012, 7:03:54 AM12/21/12
to py-le...@googlegroups.com
I seem to already have implemented exactly this. Works for both DB objects and Snapshots.

>>> db = leveldb.LevelDB('.')
>>> db.Get('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError
>>> db.Get('hello', default = 'yes')
'yes'
>>>

have fun,

Árni Már
Reply all
Reply to author
Forward
0 new messages