¿Por qué 0 <() evalúa a True en Python?
Inadvertidamente escribítime.clock<()
siendo la respuesta del intérprete de Python 2.7:True
. El siguiente código ejemplifica el comportamiento:
>>> repr(time.clock)
'<built-in function clock>'
>>> time.clock<()
True
Además:
>>> import sys
>>> sys.maxint < ()
True
>>> map(lambda _:0<_,((),[],{}))
[True, True, True]
A diferencia de:
>>> 1<set(())
TypeError: can only compare to a set
Pregunta:Además de por qué, ¿hay un significado práctico o propósito de un vacío?list
, tuple
odict
¿Evaluando como si fueran mayores que cualquier número?
Actualizar:
Viktor Señaló que las direcciones de memoria se comparan por defecto:
>>> map(lambda _:(id(0),'<',id(_)),((),[],{}, set([])))
[(31185488L, '<', 30769224L), (31185488L, '<', 277144584L), (31185488L, '<', 279477880L), (31185488L, '<', 278789256L)]
A pesar del orden aparente,Esto es incorrecto.
Martijn Pieters señala queSin un operador de comparación explícito definido, Python 2 se compara por Números y Nombres de tipo, con los números con la prioridad más baja.
Esto no sugiere qué métodos internos exactos se están invocando. Véase también este útil perohilo no concluyente:
En un IPython 2.7.5 REPL
>>> type(type(()).__name__)
Out[15]: str
>>> type(()) < 10
Out[8]: False
>>> 10 < type(())
Out[11]: True
#as described
>>> type(()) < type(())
Out[9]: False
>>> type(()) == type(())
Out[10]: True
However:
>>> 'somestr' .__le__(10)
Out[20]: NotImplemented
>>> 'somestr' .__lt__(10)
Out[21]: NotImplemented
>>> int.__gt__
Out[25]: <method-wrapper '__gt__' of type object at 0x1E221000>
>>> int.__lt__
Out[26]: <method-wrapper '__lt__' of type object at 0x1E221000>
>>> int.__lt__(None)
Out[27]: NotImplemented
#.....type(...), dir(...), type, dir......
#An 'int' instance does not have an < operator defined
>>> 0 .__lt__
Out[28]: AttributeError: 'int' object has no attribute '__lt__'
#int is actually a subclass of bool
>>>int.__subclasses__()
Out: [bool]
#str as the fallback type for default comparisons
>>> type(''.__subclasshook__)
Out[72]: builtin_function_or_method
>>> dir(''.__subclasshook__)
Out[73]:
['__call__',
'__class__',
'__cmp__',
'__delattr__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__le__',
'__lt__',
'__module__',
'__name__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__self__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__']
#IPython is subclassing 'str'
>>> str.__subclasses__()
Out[84]: [IPython.utils.text.LSString]