Hacker News new | ask | show | jobs
by pandaxtc 903 days ago
This isn't true, even if you define your own types/classes you still can't add them together willy nilly unless you (or a superclass) explicitly defined an addition operator. The Python language itself will never implicitly coerce a type for you, not even for floating point and integer addition. [0]

[0] https://www.pythonmorsels.com/type-coercion/

2 comments

You're right. Classes don't even provide such operators by default:

  >>> class Foo:
  ...     ...
  ...
  >>> class Bar:
  ...     ...
  ...
  >>> a = Foo()
  >>> b = Bar()
  >>> a+b
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  TypeError: unsupported operand type(s) for +: 'Foo' and 'Bar'
If anything, the complaint is that pre-type-hinted Python was too quick to raise a TypeError without helping you know what types it was expecting. The only case I can think of where it was too lenient was where Python 2 conflated strings and bytes. That change was 90% of the pain of the Python 3 upgrade, and now they're different types.
I was speaking generally not specifically about addition. If you create new types and especially new operations on those types, then it will be up to you to add runtime "type checks" to avoid other failures. Try defining equality for a Point class for an example.