3

I can call str methods on string literal. But I cannot call int methods on a integer number literal:

Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 
>>> 1.bit_length()
  File "<stdin>", line 1
    1.bit_length()
               ^
SyntaxError: invalid syntax
>>> a = 1
>>> a.bit_length()
1
>>> ', '.join(['1', '2'])
'1, 2'
>>> 

Why is that?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
warvariuc
  • 57,116
  • 41
  • 173
  • 227

1 Answers1

10

Python treats 1. as a beginning of a float number, but fails to parse the rest of the line. Change it to

(1).bit_length()

by enclosing the number literal with parenthesis, we make sure that python evaluates the expression within the parens, which is 1 and call the method on that number.

Python defines floating point literal like this

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

As per that definition, the lexical analyzer thinks that 1.bit_length() would be a float literal, since 1. matches the [intpart] fraction's beginning. But the rest of the line doesn't match. That is why it fails.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497