Problems using struct pack/unpack in files, and reading them.

Steven D'Aprano steve at pearwood.info
Sat Nov 14 00:40:41 EST 2015


On Sat, 14 Nov 2015 02:01 pm, Chris Angelico wrote:

> On Sat, Nov 14, 2015 at 1:40 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>> On Sat, 14 Nov 2015 09:42 am, Chris Angelico wrote:
>>
>>> However, this is a reasonable call for the abolition of unary plus...
>>
>> The only way you'll take unary plus out of Python is by prying it from my
>> cold, dead hands.
>>
>>
>> BTW, unary minus suffers from the same "problem":
>>
>> x =- y  # oops, meant x -= y
>>
>> If anything, this is an argument against the augmented assignment
>> short-cuts, rather than the operators.
> 
> Yes, unary minus has the same issue - but it's a lot more important
> than unary plus is. In ECMAScript, unary plus means "force this to be
> a number"; what's its purpose in Python?


Python has operator overloading, so it can be anything you want it to be.
E.g. you might have a DSL where +feature turns something on and -feature
turns it off.


Decimal uses it to force the current precision and rounding, regardless of
what the number was initiated to:


py> from decimal import *
py> setcontext(Context(prec=5))
py> d = Decimal("12.34567890")
py> print(d, +d)
12.34567890 12.346


Counter uses it to strip zero and negative counts:


py> from collections import Counter
py> d = Counter(a=3, b=-3)
py> print(d)
Counter({'a': 3, 'b': -3})
py> print(+d)
Counter({'a': 3})


I would expect that symbolic maths software like Sympy probably has use of a
unary plus operator, but I'm not sure.


It's probably too late now, but if I had designed the Fraction class, I
would have made it inherit from a pure Rational class that didn't
automatically normalise (there are interesting operations that rely on
distinguishing fractions like 1/2 and 2/4), and have + perform
normalisation:

x = Rational(2, 4)
print(x, +x)
=> prints 2/4 1/2


Likewise one might use unary plus to normalise polar or cylindrical
coordinates, etc.

I might consider stealing an idea from Perl and Javascript, and have unary
plus convert strings to a number:

+"123" 
=> returns int 123
+"1.23"
=> returns float 1.23



-- 
Steven




More information about the Python-list mailing list