Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what methods does `foo < bar < baz` actually invoke?

In python we can say:

if foo < bar < baz:
    do something.

and similarly, we can overload the comparision operators like:

class Bar:
    def __lt__(self, other):
        do something else

but what methods of the types of the operands of those interval comparisions are actually called? is the above equivalent to

if foo.__lt__(bar) and bar.__lt__(baz):
    do something.

Edit: re S.Lott, Here's some output that helps to illustrate what actually happens.

>>> class Bar:
    def __init__(self, name):
        self.name = name
        print('__init__', self.name)
    def __lt__(self, other):
        print('__lt__', self.name, other.name)
        return self.name < other.name

>>> Bar('a') < Bar('b') < Bar('c')
('__init__', 'a')
('__init__', 'b')
('__lt__', 'a', 'b')
('__init__', 'c')
('__lt__', 'b', 'c')
True
>>> Bar('b') < Bar('a') < Bar('c')
('__init__', 'b')
('__init__', 'a')
('__lt__', 'b', 'a')
False
>>> 
like image 937
SingleNegationElimination Avatar asked Nov 17 '10 01:11

SingleNegationElimination


People also ask

What does foo bar do?

In the world of computer programming, "foo" and "bar" are commonly used as generic examples of the names of files, users, programs, classes, hosts, etc. Thus, you will frequently encounter them in manual (man) pages, syntax descriptions, and other computer documentation.

Why do programmers use foo bar?

“Foo” and “bar” are two of the most commonly used metasyntactic variables. These are terms used as placeholder names for variables in coding and programming. They don't really mean anything as words and are just used in place of a more accurate name, generally for purposes of convenience.

What is foo and bar in Python?

Foo, bar, and baz are used as placeholders when giving examples in programming. It's like placeholder names that refer to objects or people when telling a story. Such as "widget" or "John Doe". The actual names are irrelevant and do not affect the message being conveyed.

Where does Foo Bar Baz come from?

Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members. Also, it seems likely the military FUBAR contributed to their popularity.


1 Answers

if foo < bar < baz:

is equivalent to

if foo < bar and bar < baz:

with one important distinction: if bar is a mutating, it will be cached. I.e.:

if foo < bar() < baz:

is equivalent to

tmp = bar()
if foo < tmp and tmp < baz:

But to answer your question, it will end up being:

if foo.__lt__(bar) and bar.__lt__(baz):
like image 143
Mike Axiak Avatar answered Oct 04 '22 10:10

Mike Axiak