9

I tried doing a Google search, as well as searching this Stack Exchange site but could not find a question relating directly to this.

The PEP 8 -- Style Guide for Python Code has lots of good style recommendations, however I don't think they mention anything about whether a space between a minus or negative sign (-) and a variable name would be more or less readable.

Question

It's a (very) minor issue, but which is considered more readable?

  • false_positive = -true_positive
  • false_positive = - true_positive

Motivation

I ask not to be trivial, but because in my past math courses I often find myself not noticing the negative sign in important equations, such as the equation for computing entropy:

entropy formula

I often don't notice the - sign before the summation, so making it stand out would be desirable.

1
  • I have never seen anyone write mathematics or code with a space between negation and its operand. Commented Mar 7, 2013 at 17:06

3 Answers 3

13

I couldn't find anything about it in the Python style guide, as you said, but searching for "unary operator spacing" brought more hits from various languages, such as this for Javascript:

No space should separate a unary operator and its operand except when the operator is a word such as typeof.

Or this for C:

Don't use spaces around unary operators, except sizeof and casts

In the Linux kernel:

Use one space around (on each side of) most binary and ternary operators, [...] but no space after unary operators:

Note that a writing style for code, which is usually written with a fixed-width font and mostly Latin characters, is quite different than that for equations, where you can find both latin and greek letters, topological constructs such as fractions or those marks surrounding that epsilon you have there, and other things that make them a whole lot more complex than code.

1
  • Thanks for the research, and for the additional keywords ("unary operator") that will help during future searches! Commented Mar 3, 2013 at 6:25
1

I've run across this before, and I used

var false_positive = 0 - true_positive

to make sure the intent is clear. That is the more readable form.

0

I think the second one is marginally less bad, because the minus sign is a little less likely to be read as part of the word; However, I think both forms are bad.

I would replace the whole thing with

false_positive = -1 * true_positive

or even

false_positive = (-1) * true_positive

in any language.

1
  • 1
    This is a good idea, but multiplication is more expensive than addition so I like @jeffbeat's 0 - true_positive better because it gets the point across in a manner that is more efficient for the machine to process. Commented Mar 7, 2013 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.