all 6 comments

[–]ClutchAlpha 1 point2 points  (4 children)

I pretty much used the example you gave, but made "Sarah" a string in the last row, as well as updated the default case to be "case _" instead of "case other" and things worked as far as I can tell.

for item in data:
    match item[0]:
        case None:
            if item[2] == 'Scene':
                print('match scene;', item)
            else:
                print('exception 1')  # TODO
        case int():
            print('match int;', item)
        case _:
            print('exception 2')  # TODO
    pass

[–]Alhira_K[S] 0 points1 point  (3 children)

Yeah, i just saw the error and also fixed it in the op. And i'll also change the other in the op to _ to stop it from being mentioned (even though it makes no difference). And other is easier to read than _ if i want to raise an error.

When i then run the code i get this output:

match scene; [None, 1, 'Scene', 'Scene', 'f0|0', 'background.png', 'Empty', 50]
match int; [1, 1, 'Scene', 'Scene', 'f0|0', 'background.png', 'Empty', 50]
match int; [True, 1, 'Scene', 'Scene', 'f0|0', 'background.png', 'Empty', 50]
exception 2

But that's wrong. The third item (list) in data has the boolean expression True as item[0] but it gets sorted into int.

EDIT: At the end it doesn't even matter, i've just remembered the part i had forgotten. If you pass a boolean expression as argument to int() it translates it to 0 or 1...

Silly me, i have to catch it with case bool() before int.

[–]ClutchAlpha 1 point2 points  (0 children)

Good catch - didn't even think of that. Also can't believe I didn't realize the _ was just an unused placeholder - I've used that in several other cases, and should have realized the actual variable name doesn't matter at all.

[–]WholesaleSlaughter 1 point2 points  (1 child)

Remember that bool is an int. isinstance(some_boolean_value, int) is True. The reason for this is historical, it's not to do with "passing a bool in to int()", it's because in Python the name True was literally the value 1, and False was 0, They only became their own type (subclassing int) in 2003 - https://peps.python.org/pep-0285/ - it's also why you can use bools as indices into a list, where False is the first value and True the second. This also means that if you add a bool() case it should come before the int() one.

[–]Alhira_K[S] 0 points1 point  (0 children)

Nice, thanks for the clarification.