Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cant read this python format ( , ) [ . . ]

Tags:

python

I'm newbie and I'm reading a snippet of code like this:

...
proto = ('http', 'https')[bool(self.https)]
...

It looks like this line is letting proto to switch between 'http' and 'https'.

But what does the ( , )[ .. ] mean? How can I make use of this style?

like image 232
Detective King Avatar asked Dec 15 '22 07:12

Detective King


2 Answers

The second element (in the brackets) is the index that will be used on the first element. So in this case, you have a single tuple:

('http', 'https')

And then a boolean that represents whether self.https is set. If it is true, the value will be 1, making the call:

('http', 'https')[1]

Which will select the https value from the tuple. This takes advantage of the fact that bool is a subclass of int, which could potentially be considered an abuse :)

In [1]: t = ('http', 'https')

In [2]: t[0]
Out[2]: 'http'

In [3]: t[1]
Out[3]: 'https'

In [4]: https_setting = True

In [5]: int(https_setting)
Out[5]: 1

In [6]: t[bool(https_setting)]
Out[6]: 'https'

In [7]: True.__class__.__bases__
Out[7]: (int,)

For a cool usage of this technique, check out 2:14 in this video (which also happens to be a great video in its own right!). It indexes a string ('^ ') instead of a tuple, but the concept is the same.

like image 188
RocketDonkey Avatar answered Dec 29 '22 22:12

RocketDonkey


It is a "switcher". This is just a short form of:

proto = 'https' if self.https else 'http'

or

if self.https:
    proto = 'https'
else:
    proto = 'http'

Also, see that you can take an item from a tuple by True and False (same as by 1 and 0):

>>> print ('http', 'https')[True]
https
>>> print ('http', 'https')[False]
http
>>> print ('http', 'https')[1]
https
>>> print ('http', 'https')[0]
http
like image 30
alecxe Avatar answered Dec 29 '22 22:12

alecxe