On Wed, Jan 13, 2021 at 5:05 PM Steven D'Aprano <st...@pearwood.info> wrote: > > On Wed, Jan 13, 2021 at 04:47:06AM +1100, Chris Angelico wrote: > > > That'd leave open > > the option for "foo() if x else foo()" to be optimized down to just > > "foo()", although I don't think that particular one is needed. > > That would be an unsafe optimization. Not all objets are representable > as truthy/falsey values, e.g. numpy arrays. > > >>> bool(a) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > ValueError: The truth value of an array with more than one element > is ambiguous. Use a.any() or a.all() > > Not even all builtin values. This is in Python 3.9: > > >>> bool(NotImplemented) > <stdin>:1: DeprecationWarning: NotImplemented should not be used in > a boolean context > True > > I believe that 3.10 makes it an error. If not 3.10, then it will surely > happen soon. But even without the change to NotImplemented, it has never > been the case that *every* object is guaranteed to be either truthy or > falsey. At least not since the Python 1.x `__nonzero__` dunder was put > into the language. >
But this is exactly where we started: with a boolification that fails, in a context where the result wouldn't actually change anything. Actually calling bool() on something will continue to have the behaviour you're describing, but if the truthiness or falsiness would make no difference, is the interpreter required to find out? ChrisA _______________________________________________ Python-Dev mailing list -- python-dev@python.org To unsubscribe send an email to python-dev-le...@python.org https://mail.python.org/mailman3/lists/python-dev.python.org/ Message archived at https://mail.python.org/archives/list/python-dev@python.org/message/IMG437FNV552XUWOQJW76A7SFAJQULEH/ Code of Conduct: http://python.org/psf/codeofconduct/