Posts: 4,653
Threads: 1,496
Joined: Sep 2016
what would be an example of a situation where code can be valid without : and valid with : and have different semantics? or can a language like Python that has optional : be possible?
if i leave out : i get a syntax error. is there a case where that does not happen?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 4,801
Threads: 77
Joined: Jan 2018
1 2 3 4 5 6 7 |
>>> L = list ( range ( 10 ))
>>> L[:: - 1 ]
[ 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ]
>>> L[: - 1 ]
[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
>>> L[ - 1 ]
9
|
Posts: 2,128
Threads: 11
Joined: May 2017
If there is a colon in the square brackets, it's an instance of slice .
A slice takes 3 arguments. [::] -> slice(None, None, None)
[::-1] -> slice(None, None, -1)
The : in the subscription is like a comma in the function call.
If you use a comma in the subscription, then the key is a tuple.
You can try it by yourself.
__class_getitem__ was introduced for typehints.
I used it because then I don't have to create an instance of the class.
It's like __getitem__ for instances.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class GetItem:
def __class_getitem__( self , key):
if isinstance (key, slice ):
print ( "Key is a slice" )
elif isinstance (key, tuple ):
print ( "Key is a tuple" )
if all ( isinstance (item, slice ) for item in key):
print ( "All items are slices" )
elif any ( isinstance (item, slice ) for item in key):
print ( "One or more items are a slice instance" )
else :
print ( "Got something else" )
return key
print (GetItem[ 1 ])
print (GetItem[:])
print (GetItem[ 0 :])
print (GetItem[ 1 : 3 ])
print (GetItem[: 2 ])
print (GetItem[:: - 1 ])
print (GetItem[:, 1 ,:])
|
Posts: 4,653
Threads: 1,496
Joined: Sep 2016
Apr-06-2021, 06:23 PM
(This post was last modified: Apr-06-2021, 06:23 PM by Skaperen.)
i didn't think about slices although a different language could require tuples be inside () and use , in place of : in the square brackets. i was thinking about the : that follow keywords like def, if, else, for, while, try. except ... well, eventually follow. what if that language looked like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class GetItem
def __class_getitem__( self , key)
if isinstance (key, slice )
print ( "Key is a slice" )
elif isinstance (key, tuple )
print ( "Key is a tuple" )
if all ( isinstance (item, slice ) for item in key)
print ( "All items are slices" )
elif any ( isinstance (item, slice ) for item in key)
print ( "One or more items are a slice instance" )
else
print ( "Got something else" )
return key
...
|
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
|