Marcin 'Qrczak' Kowalczyk wrote: > Stefan Behnel <[EMAIL PROTECTED]> writes: > >> So, if hashable() returns True, it means that a) the designer didn't >> care about switching it off or b) there are cases where it works, so >> it makes sense to try calling it. > > If the code can successfully work with either hashable or non-hashable > objects, it can just always try to call it (and deal with potential > failure), rather than test first and then check for failure anyway.
The use cases are where the check and the subsequent usage are in different parts of the code - by doing the check early, you can flag some errors near the point where they are introduced (i.e. the object passed in definitely doesn't support the needed protocol), rather than doing it later where the traceback will actually lead you on a wild goose chase. This case is strongest for callable() - calling an object early generally won't be an option, especially if it is a callback that should only be called after a particular event has occurred. Note that in the case of a bug in the callback function itself, the traceback will start from inside the function, but if the callback isn't actually callable, you have to somehow figure out which code was responsible for registering the callback in the first place. Flagging that something that definitely isn't callable has been passed as a callback parameter at the time it is passed in, rather than when the callback is invoked, will make such errors far easier to resolve. Use cases for a "may be hashable" pretest are much weaker (and typically hypothetical), but there are cases where it makes a certain amount of sense. For example, if you have a set-based fast path if all the objects being handled are hashable, and a list-based slow path if one or more aren't hashable, and the hashes themselves may be expensive to calculate (e.g. some of the objects may be large strings) then it may make sense to perform a precheck to ensure that all of the objects are at least *potentially* hashable before you try to put any of them into a set. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --------------------------------------------------------------- http://www.boredomandlaziness.org _______________________________________________ Python-3000 mailing list Python-3000@python.org http://mail.python.org/mailman/listinfo/python-3000 Unsubscribe: http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com