danvk
danvk

Reputation: 16955

Why is this valid Python?

This code:

bounding_box = (
    -122.43687629699707, 37.743774801147126
    -122.3822021484375, 37.80123932755579
)

produces the following value:

(-122.43687629699707, -84.63842734729037, 37.80123932755579)

There are three values because I forgot a trailing comma on the first line. Surprisingly, Python accepts this and adds the second and third numbers together!

Is this something like string literal concatenation but for numbers? Why would this ever be the desired behavior?

Upvotes: 3

Views: 197

Answers (3)

Lucas
Lucas

Reputation: 5069

You have a newline, but no new indent. It doesn't throw an error because there is no indentation issues, and it doesn't even acknowledge the newline when doing the subtraction.

What if you're trying to keep your text all within the window? The delimiter between values is a comma, not a newline. That's why this is the desired behaviour.

Upvotes: 0

Josh Kelley
Josh Kelley

Reputation: 58392

Without the newlines, and dropping the decimals for clarity:

bounding_box = (-122, 37 - 122, 37 )

In other words, what was supposed to be a comma then unary minus was parsed as a subtraction operator.

Upvotes: 3

Pythonista
Pythonista

Reputation: 11645

What happens is simple. In the following assignment

bounding_box = (
    -122.43687629699707, 37.743774801147126
    -122.3822021484375, 37.80123932755579
)

Is equivalent to

bounding_box = (-122.43687629699707, **37.743774801147126-122.3822021484375**, 37.80123932755579)

So, the two values are just being subtracted, and hence produce a 3-tuple.

Upvotes: 10

Related Questions