Why 00 is a valid integer in Python?

Question:

In the Python documentation :

integer      ::=  decinteger | bininteger | octinteger | hexinteger
decinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+
octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+
hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::=  "1"..."9"
digit        ::=  "0"..."9"
bindigit     ::=  "0" | "1"
octdigit     ::=  "0"..."7"
hexdigit     ::=  digit | "a"..."f" | "A"..."F"

I can’t get why 00 is a valid integer with those definitions? It seems a nonzerodigit must be the leading digit, though:

>>> isinstance(00, int)
True

And maybe the same question: why 0 is valid?

Asked By: david

||

Answers:

What you’re missing is that the | notation for alternatives has lowest precedence. So decinteger is split into two distinct productions:

  • nonzerodigit (["_"] digit)*
  • "0"+ (["_"] "0")*

The first is for numbers not starting with 0, it allows any digits in the rest of the number. The second is for numbers starting with 0, it only allows numbers that are all 0. Both allow optional _ characters to be interspersed between digits for easier reading.

So 0, 00, 000, etc. are allowed as valid decimal integers by the second production. And their values are all zero.

Some EBNF documentation put alternatives on separate lines to make it easier to see the breakdown. The Python documentation has chosen this more compact format.

Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.