[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
- Previous message: [Python-Dev] Getting values stored inside sets
- Next message: [Python-Dev] Getting values stored inside sets
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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:
- Try "a.op(b)"
- If "a.op" doesn't exist or the call returns NotImplemented, try "b.rop(a)"
- If "b.rop" doesn't exist or the call returns NotImplemented, raise TypeError identifying "type(a)" and "type(b)" as unsupported operands for OP
- 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:
- Try "a = a.iop(b)"
- 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:
if "type(b)" is a strict subclass of "type(a)", then "b.rop" is tried before "a.op". This allows subclasses to ensure an instance of the subclass is returned when interacting with instances of the parent class.
rich comparisons are associated into op/rop pairs as follows: eq/eq (i.e. a == b is considered equivalent to b == a) ne/ne (i.e. a != b is considered equivalent to b != a) lt/gt (i.e. a < b is considered equivalent to b > a) le/ge (i.e. a <= b is considered equivalent to b >= a)
rpow is never invoked for the 3 argument form of pow(), as the coercion rules only apply to binary operations. In this case, a NotImplemented return from the call to pow is converted immediately into a TypeError. """
Cheers, Nick.
-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
- Previous message: [Python-Dev] Getting values stored inside sets
- Next message: [Python-Dev] Getting values stored inside sets
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]