Python bool (Ellipsis) and bool (No)

I do not understand how Ellipsis and None handled differently by bool() , when both seem to be the same in terms of the corresponding attributes to verify the truth.

 >>> bool(Ellipsis) True >>> bool(None) False >>> any([hasattr(Ellipsis, attr) for attr in ['__len__', '__bool__', '__nonzero__']]) False >>> any([hasattr(None, attr) for attr in ['__len__', '__bool__', '__nonzero__']]) False 
  • Is there anything else that I am missing that is used to verify the truth?

  • Are there any other objects (besides None ) that evaluate to False that don't implement any of __len__ or __nonzero__ ?

+4
source share
2 answers

bool(x) True if x is an object without one of the magic methods you mentioned that returns False . Therefore, Ellipsis is rated True .

None with special trims in bool() and returns it False .

Details:

bool() uses the PyObject_IsTrue() API function, which in 2.7.2 looks like this:

 int PyObject_IsTrue(PyObject *v) { Py_ssize_t res; if (v == Py_True) return 1; if (v == Py_False) return 0; if (v == Py_None) return 0; else if (v->ob_type->tp_as_number != NULL && v->ob_type->tp_as_number->nb_nonzero != NULL) res = (*v->ob_type->tp_as_number->nb_nonzero)(v); else if (v->ob_type->tp_as_mapping != NULL && v->ob_type->tp_as_mapping->mp_length != NULL) res = (*v->ob_type->tp_as_mapping->mp_length)(v); else if (v->ob_type->tp_as_sequence != NULL && v->ob_type->tp_as_sequence->sq_length != NULL) res = (*v->ob_type->tp_as_sequence->sq_length)(v); else return 1; /* if it is negative, it should be either -1 or -2 */ return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); } 
+8
source

From the Python Data Model :

If the class defines neither len () nor nonzero (), then all instances of it are considered true.

None evaluates to false because the built-in type is specified for it. You did not define __len__() or __nonzero__() on Ellipsis , as you said. If you want it to be evaluated as false,

 class Ellipsis(...): #... def __nonzero__(self): return False # or def __len__(self): return 0 
+1
source

Source: https://habr.com/ru/post/1389182/


All Articles