On Jun 4, 12:42 pm, Ian Kelly <ian.g.ke...@gmail.com> wrote: > > By this manner, we can roll three common tests into one > > method: > > * Boolean conversion > > * member truthiness for iterables > > * type checking > How exactly does this is_valid method perform the first two? Are you > suggesting that an empty sequence should not be considered "valid"?
I'm suggesting that the rules for Python's current "implicit conversion to Boolean" simply be moved into a "explicit function" named "isvalid", that also does a type check. Here is some Python code that might help you understand. py> def isvalid(object_, type_): ... if isinstance(object_, type_) and object_: ... return True ... return False py> isvalid([], list) False py> isvalid([1], list) True py> isvalid(0, int) False py> isvalid(1, int) True py> isvalid({}, dict) False py> isvalid("", str) False py> isvalid(" ", str) True Now, let's go back to my earlier example of where i was expecting a list but got a string instead. If i use Python's current implicit conversion to Boolean my code will do something i don't want it to do. py> lst = " " py> if lst: ... print("I'm a liar") ... else: ... print("I'm honest") I'm a liar But unlike this simple example (which failed quickly) in the real world, it may not fail for a long time. And when it does fail, you will be pulling your hair out tracking down the origin of the bug. If however i use my "isvalid" function, my conditional will not lie to me: py> lst = " " py> if isvalid(lst, list): ... print("I'm a liar") ... else: ... print("I'm honest") I'm honest Now. You're not always going to need to "isvalid" function. Sometimes you just need to test type, sometimes you just need convert to Boolean, and sometimes you can just fly by the seat of your pants. The point is, remove implicitly and inject explicitly. Furthermore: If the current "implicit conversion to Boolean" can be optimized by Python, then there is no reason why an explicit "isvalid" function cannot -- any talk to the contrary is just BS. If you still feel that this idea is garbage, then, keep on writing your sloppy code. My proposal is the best method to handle the problems that arise with duck typed languages in a manner that is not restrictive or laborious -- it's actually quite elegant. *school-bell-rings* -- http://mail.python.org/mailman/listinfo/python-list