więc o to odpowiednik == PHP
def php_cmp(a, b):
if a is None and isinstance(b, basestring):
a = ""
elif b is None and isinstance(a, basestring):
b = ""
if a in (None, False, True) or b in (None, False, True):
return bool(a) - bool(b)
if isinstance(a, (basestring, int, long, float)) and isinstance(b, (basestring, int, long, float)):
try:
return cmp(float(a), float(b))
except ValueError:
return cmp(a,b)
if isinstance(a, (tuple,list)) and isinstance(b, (tuple,list)):
if len(a) != len(b):
return cmp(len(a),len(b))
return cmp(a,b)
if isinstance(a, dict) and isinstance(b, dict):
if len(a) != len(b):
return cmp(len(a),len(b))
for key in a:
if key not in b:
raise AssertionError('not compareable')
r = cmp(a[key], b[key])
if r: return r
return 0
if isinstance(a, (basestring, int, long, float)):
return 1
if isinstance(b, (basestring, int, long, float)):
return -1
return cmp(a,b)
def php_equal(a, b):
return php_cmp(a,b) == 0
Test:
>>> php_equal(2, '2')
True
ze względu na inny model obiektowy i realizacja tablica ta nie jest w 100% poprawne, ale powinno dać ci pojęcie, jakie mogą wystąpić problemy z automatyczną konwersją typów dla compa rison.
@frostnational Nie, nie jest. – thefourtheye
Prawda. Ale w PHP. Mimo że typ zmiennej jest inny, zwraca TRUE. W języku Python zwraca FALSE – Realdeo
Jest to odpowiednik bardzo długiej i skomplikowanej sekwencji warunkowych konwersji w zależności od typów argumentów i ich wartości w pozornie arbitralnych (a więc prawie niemożliwych do uproszczenia) sposobach. Chciałbym żartować. – delnan