The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Chris Angelico rosuav at gmail.com
Tue Mar 22 21:21:50 EDT 2016


On Wed, Mar 23, 2016 at 12:14 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> I mean, is a function allowed to still return True or False, or just
>> False? (Or perhaps just nothing if the exception mechanism can signal
>> either.)
>
>
> You can answer this question yourself by looking at what functions are
> provided in the standard library and built-ins:
>
> py> "hello world".find("goodbye")
> -1
> py> "hello world".startswith("goodbye")
> False

To add to the "experiment" advice, a general rule of thumb: Any
function/method that appears to be asking a yes/no question should be
happy to return True/False for the two answers. It can still raise if
the question doesn't make sense:

>>> "hello world".startswith(3.14159)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: startswith first arg must be str or a tuple of str, not float
>>> "hello world".startswith(b"\x41")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: startswith first arg must be str or a tuple of str, not bytes

ChrisA



More information about the Python-list mailing list