Can not read this format python (,) [.,]

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

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

This line seems to allow proto switch between 'http' and 'https' .

But what does ( , )[ .. ] mean? How can i use this style?

+4
source share
4 answers

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

 ('http', 'https') 

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

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

which selects the https value from the tuple. This exploits the fact that bool is a subclass of int , which could potentially be considered 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 use of this technique, check out 2:14 in this video (which is also a great video of your choice!). It indexes a string ( '^ ' ) instead of a tuple, but the concept is the same.

+10
source

This is a "switch." This is just a short form:

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

or

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

Also see that you can take an element from the True and False tuple (same as 1 and 0 ):

 >>> print ('http', 'https')[True] https >>> print ('http', 'https')[False] http >>> print ('http', 'https')[1] https >>> print ('http', 'https')[0] http 
+1
source

This is a dense style (and not too popular), using the fact that booleans can only be 0 (False) or 1 (True), which are exactly the indices of a list or list of null indices.

It may be a little confusing that the index is listed as bool , but:

 >>> int(bool(False)) 0 >>> int(bool(True)) 1 

Also

... Booleans are a subtype of prime integers.

From: http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex

+1
source
 ('http','https') 

is a tuple. Like all tuples, its elements can be addressed by indices (0 and 1 in this case).

 bool(self.https) 

converts self.https to boolean. However, in Python, booleans are represented as integers 0 (for false) and 1 (for true). Thus,

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

is equivalent to:

 ('http','https')[0] # ('http') when self.https is false, or ('http','https')[1] # ('https') when self.https is true 

or

 'https' if self.https else 'http' 

which can be roughly understood as

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

The form 'https' if self.https else 'http' was introduced with Python 2.5. Previously, several programs, as you have shown, were very common among Python programmers.

0
source

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


All Articles