PEP 285: Adding a bool type

Stuart Bishop zen at shangri-la.dropbear.id.au
Sat Apr 6 22:53:55 EST 2002


On Sunday, April 7, 2002, at 04:39  AM, Laura Creighton wrote:

> Mark McEahern writes:
>> [Laura Creighton]
>>> [...]  I am rejecting the existence of booleans in the language
>>> because it is too hard to teach how to use them properly.
>>
>> How do you use them properly?
>>
>> Suppose I want to validate users.  I might write something like this:
>>
>> 	def isValid(user, password):
>> 		if ...:
>> 			return True
>> 		else:
>> 			return False
>
> My pleasure, especially since this is such a cool example.  You have
> just shot yourself in the foot, and do not know it.  When you have
> shipped your isValid function, across the world to your 10,000 clients,
> you will discover this.
>
> Your boss comes in and says, oh, Mark, we need a change to that
> isValid function.  We need to return 3 states, Valid, Invalid, and
> Valid-but-You-Don't-Have-Access-Because-You-Didn't-Pay-Your-Bill.
>
> What do you do now?

You correct them. isValid is returning a perfectly valid
boolean state - either the username, password combination
is valid or it isn't. This makes this function useful.
At some point, my application needs to make a decision
'can I log in or not', and it has to get a boolean answer.

If I make my isValid function return a state rather than
a boolean, then every single piece of code that uses
isValid will then need to encode the business logic about
what to do if it gets these states. Everytime I add a new
state ('Valid-but-only-on-weekends','Valid-if-they-are-on-campus'),
every bit of code that calls isValid now needs to be updated with
the new business logic. By changing the possible return values,
the API has been changed

If my isValid function contains the business logic and can only
return True/False, then I can update it whenever it is needed
and not need to update every single call of this function to
handle the new state.

> case.  Don't artificially limit yourself to 2 values because your
> vision at the time only extended to 2 values.  The one thing constant
> in this world is change.   If you don't need a third value, somebody
> else will, later.  Integers are your friends.

I constantly see functions that should return boolean. Looking
at the builtin functions page of the Python library for example,
hasattr, callable, isinstance and issubclass should all return
a boolean. Saying they return 0,1 and maybe something additional
in the future makes my code unnecessarily complex:

if callable(foo) == 1:
	result = foo()
elif callable(foo) == 0:
	result = foo
else:
	raise RuntimeError('Oops! I havn't a clue what is happening!')

--
Stuart Bishop <zen at shangri-la.dropbear.id.au>
http://shangri-la.dropbear.id.au/






More information about the Python-list mailing list