0

I was experimenting with the built-in methods __lt__(), __gt__() and __eq__(). When I tried to do the operation directly, like 2.__lt__(5), it gave output as invalid syntax instead I was expecting it to give as True.

when these values are being referenced through name bindings, it works fine, Like above

a = 2
b = 5
a.__lt__(b)

gives True as output, which is expected.

when we check the type of the object, in both scenarios it is the same as <class 'int'>

type(2)
<class 'int'>

type(a)
<class 'int'>

why does it differ when the same type of objects are being passed to the built-in methods?

  • 2
    You need `(2)`... – user202729 Jan 13 '21 at 06:57
  • 2
    Does this answer your question? [Why is "1.real" a syntax error but "1 .real" valid in Python?](https://stackoverflow.com/questions/31037609/why-is-1-real-a-syntax-error-but-1-real-valid-in-python) – user202729 Jan 13 '21 at 06:59
  • Yes, @user202729. that along with the explanation by Adam Smith places the concept in place to understand well. – Vaitesh Selvaraj Jan 13 '21 at 07:24
  • Perhaps [python - Accessing attributes on literals work on all types, but not `int`; why? - Stack Overflow](https://stackoverflow.com/questions/33054229/accessing-attributes-on-literals-work-on-all-types-but-not-int-why?noredirect=1&lq=1) is a better question. – user202729 Jan 13 '21 at 07:30
  • "directly on the values of the object". That isn't what `1` is. `1` is a literal, which *evaluates* to an object. The same as a simple `a` expression. It is no more "direct" than using `a`. The type isn't relevant, you are getting a *syntax error*. – juanpa.arrivillaga Jan 13 '21 at 07:33

1 Answers1

2

2.__something__ is ambiguous, because 2.3 is valid syntax for a float literal. Indeed since you can use single underscores almost anywhere in numeric literals (e.g. 1_000_000 == 1000000 and 3.141_59 == 3.14159), it's difficult to create consistency without forcing some sort of special syntax. You can remove the ambiguity by parenthesizing the expression:

(2).__lt__(5)

then it behaves equivalently to other objects.

[2, 3, 4].pop()
# or
"this, that, the other".split(',')
# etc...
Adam Smith
  • 52,157
  • 12
  • 73
  • 112