Why 00 is a valid integer in Python?

66 Views Asked by At

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?

1

There are 1 best solutions below

0
Barmar On BEST ANSWER

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.