numeric emulation and __pos__

Ethan Furman ethan at stoneleaf.us
Tue Jul 8 13:34:04 EDT 2008


Mark Dickinson wrote:
> On Jul 8, 12:12 am, Ethan Furman <et... at stoneleaf.us> wrote:
> 
>>1) Any reason to support the less common operators?
>>        i.e. <<, >>, &, ^, |
> 
> No reason to support any of these for a nonintegral
> nonbinary type, as far as I can see.
> 
>>2) What, exactly, does .__pos__() do?  An example would help, too.
> 
> Very little:  it implements the unary + operator, which
> for most numeric types is a no-op:
> 
>>>>+5.0
> 
> 5.0

Anybody have an example of when the unary + actually does something?
Besides the below Decimal example.  I'm curious under what circumstances
it would be useful for more than just completeness (although
completeness for it's own sake is important, IMO).

> So you could safely implement it as:
> 
> def __pos__(self):
>     return self
> 
> By the way, have you met the Decimal type?  It also
> keeps track of significant zeros.  For example:
> 
>>>>from decimal import Decimal
>>>>Decimal('1.95') + Decimal('2.05')
> 
> Decimal("4.00")

Significant zeroes is not quite the same as significant digits (although
Decimal may support that too, I haven't studied it).  The difference
being, for example, the following:

>>> from decimal import Decimal
>>> first = Decimal("3.14")
>>> second = Decimal("5.2")
>>> first * second
Decimal("16.328")

>>> from measure import Measure
>>> third = Measure("3.14")
>>> fourth = Measure("5.2")
>>> third * fourth
Measure("16")

In other words, any calculated value cannot be more accurate than the
least accurate input (5.2 in the case above, which hase two significant
digits).

> (Note that the output includes the extra zeros...)
> Interestingly, in Decimal the __pos__ operation isn't a no-op:
> it rounds a Decimal to the current context, and it also
> (mistakenly, in my opinion) changes -0.0 to 0.0:
> 
> 
>>>>+Decimal('-0.0')
> 
> Decimal("0.0")
> 
>>>>+Decimal('123456789123456789123456789123456789')
> 
> Decimal("1.234567891234567891234567891E+35")
> 
> Mark

--
Ethan




More information about the Python-list mailing list