Why is this a syntax error for calling a method in a numeric literal in Python?

I can call methods for numbers only when I bind them to a name:

>>> a = 5
>>> a.bit_length()
3

I can call string literal methods:

>>> 'Hello World'.lower()
'hello world'

But I cannot call methods for numeric literals:

>>> 5.bit_length()

There is a SyntaxError. Is there a practical reason for this or historical?

Edit Just found this related question that shows workarounds (which have already been suggested here as well). I think this also answers the main question - with simple workarounds, there were probably not enough advantages to make the grammar more complex (and harder to parse) to make this work.

+4
2

: ,

floatnumber   ::=  pointfloat | exponentfloat
pointfloat    ::=  [intpart] fraction | intpart "."
exponentfloat ::=  (intpart | pointfloat) exponent
intpart       ::=  digit+
fraction      ::=  "." digit+
exponent      ::=  ("e" | "E") ["+" | "-"] digit+

Python 5., , [intpart] fraction | intpart ".". , , fraction. .

5 .bit_length()

,

(5).bit_length()
+7

, , , fraction .

, :

pointfloat    ::=  [intpart] fraction | intpart "."

, , . - 5., , , 5.bit_length, 2 : 5. ( is, float 5.0) bit_length; , , ​​python.

float, :

>>> 5.0.hex()
'0x1.4000000000000p+2'
>>> 5..hex()
'0x1.4000000000000p+2'

int, 5 ., .

+1

Source: https://habr.com/ru/post/1535901/


All Articles