osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code


On Tue, 19 Sep 2017 09:22:21 +0200, Antoon Pardon wrote:

> But the problem is that the following two pieces of code don't do the
> same in Python.
> 
> if x: pass 
> if x is True: pass
> 
> Sometimes I need that second statement 

"Need" is a funny thing. If all you are doing is testing the truthiness 
of x, which is what it looks like to me, why do you care that it is a 
bool, rather than an int 1 or a float or any other object?

You probably don't insist that your lists are *actual* lists, any list-
like object with the right interface will do. You probably don't insist 
that your iterators are *actual* IteratorType objects, which is good 
because there's no such thing and iterators come in many different types, 
all quacking and swimming the same.

So why insist on True and False alone? That's a code smell.

But okay, I'll give you the benefit of the doubt and assume you have a 
good reason. Okay, that's easy to fix:


# We require actual True here, not just a truthy value.
if x is True: pass


If anyone insists on questioning this, you can just say "Yes, I hear you, 
but I have reasons, and you would need to understand our entire project 
to understand them, so just trust me."

And the problem is solved.


-- 
Steven D'Aprano
?You are deluded if you think software engineers who can't write 
operating systems or applications without security holes, can write 
virtualization layers without security holes.? ?Theo de Raadt