Strict comparison

后端 未结 5 1825
再見小時候
再見小時候 2021-01-17 11:43

In javascript, there are strict comparison operators op1 === op2 and op1 !== op2 that will compare both type and value. Is there a pythonic way of

5条回答
  •  旧巷少年郎
    2021-01-17 12:01

    You can also use the operator module if you want to be super strict. https://docs.python.org/2/library/operator.html

    >>> import operator
    >>> operator.eq(True, 1)
    True
    >>> operator.is_(True, 1)
    False
    

    Some of the answers in here are wrong. Python for instance, will not differentiate between some types, for the purpose of some comparisons.

    For example:

    >>> 1 == 1.0
    True
    >>> operator.eq(1, 1.0)
    True
    >>> operator.is_(1, 1.0)
    False
    

    Is works better than eq (or ==), but it is dependent on a variable being pointers on the same value, which means there's lots of cases you wouldn't like.

    If you want to go deep, implementing this in a shorthand manner, something like this: http://code.activestate.com/recipes/384122/ will let you "kind of" build your own operators.

提交回复
热议问题