Hacker News new | comments | show | ask | jobs | submit login
Python FAQ: Equality (veekun.com)
91 points by easonchan42 1653 days ago | hide | past | web | 10 comments | favorite

OP has: "did you call SomeClass() twice? Then a is b will always be False."

Not quite. SomeClass can have an implementation of __new__ which returns the same object upon every invocation. In this case "SomeClass() is SomeClass()" will be True. People sometimes do this and call SomeClass a "singleton".

Yeah, I wasn't crazy about the implication that str and int only do this via special built-in magic. In reality, you can overload __new__ to return whatever you want, including object interning.

In the first example under "When to use which", the reason you want to set a default argument in a function to None, check if it is None, and then set it to an empty list is explained here:


In short, it can be bad to set default arguments to mutable objects because the function keeps using the same object in each call.

Good stuff. I was playing around with ordinality of language built-ins recently and found unintuitive results for Python (https://github.com/rflynn/wat/blob/master/src/py.ord.png). As your article mentions there is a fine line between language and implementation detail.

    >>> u"" > () > "" == u""


CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

Worth mentioning that this was fixed/removed in Python 3.x

  >>> "" > ()
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  TypeError: unorderable types: str() > tuple()

> Use arg is None when you have a function with an argument defaulting to None. That’s okay, because there’s only oneNone.

In most real cases you want to get out if arg is either None offer any false value, so maybe "if not arg" ?

> For testing whether two classes, functions, or modules are the same object, is is okay. Stylistic choice.

If "is" is not better than = I would advise against it in all cases where it is not necessary: always use = except when you do tricky things. The argument that = can be overridden is wrong: if it really is the case, just use another library or fix it. You should nor write defensive code at this level.

I like Kent Pitman's explanation of why there cannot be One Universal Equality in Lisp:


It's worth noting that the problems he mentions are specific to Common Lisp. Other lisps make it possible to implement egal.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact