[Python-Dev] Documenting the Py3k coercion rules (was Re: Getting values stored inside sets) (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Sat Apr 4 07:54:23 CEST 2009


Raymond Hettinger wrote:

[Nick Coghlan] It doesn't quite work the way RDM desribed it - he missed a step. Thanks for the clarification. We ought to write-out the process somewhere in a FAQ.

The closest we currently have to that is the write-up of the coercion rules in 2.x:

http://docs.python.org/reference/datamodel.html#id5

Unfortunately, that mixes in a lot of CPython specific special cases along with the old coerce() builtin that obscure the basic behaviour for op and rop pairs.

Here's an initial stab at a write-up of the coercion rules for Py3k that is accurate without getting too CPython specific:

""" Given "a OP b", the coercion sequence is:

  1. Try "a.op(b)"
  2. If "a.op" doesn't exist or the call returns NotImplemented, try "b.rop(a)"
  3. If "b.rop" doesn't exist or the call returns NotImplemented, raise TypeError identifying "type(a)" and "type(b)" as unsupported operands for OP
  4. If step 1 or 2 is successful, then the result of the call is the value of the expression

Given "a OP= b" the coercion sequence is:

  1. Try "a = a.iop(b)"
  2. If "a.iop" doesn't exist or the call returns not implemented, try "a = a OP b" using the normal binary coercion rules above

Special cases:

Cheers, Nick.

-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia



More information about the Python-Dev mailing list