osdir.com


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

[Tutor] beginning to code


On Tuesday, September 19, 2017 at 4:41:01 PM UTC+5:30, Antoon Pardon wrote:
> Op 19-09-17 om 11:22 schreef Steven D'Aprano:
> > Except for bools, where people freak out and are convinced the world will 
> > end if you just ask an object "are you true or false?". 
> >
> > Perhaps just a *tiny* exaggeration *wink*
> 
> On the other hand, python is very eager to convert objects to a bool. For
> strings and iterators you are expected to write a dunder method. If you
> think it makes no sense to see specific instances as true or false, you
> have to explicitly write a __bool__ that raises an exception. I think
> it would have been a better choice that a TypeError would have been
> raised if __bool__ wasn't defined.

How exceptional is python's choice to NOT raise exceptions can be seen by examples:

>>> [] + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> [] < 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: list() < int()
>>> 1[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
>>> 2 < []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < list()
>>> len(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> [x for x in 1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> -[]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: 'list'


>>> [] or []
[]
# Ah well... Same category as...

>>> ("empty" if [] else "nonempty")
'nonempty'
>>>