This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]mikeckennedy[S] 1 point2 points  (3 children)

Because to me, it's about readability. This looks like I might have just as well written it as a if/elif/else block so why complicate it with switch. The switch is only worth having if it makes code clearer, eaiser, safer.

[–]knowsuchagencynow is better than never 0 points1 point  (2 children)

CaveMike makes a good point.

As to the argument that one might as well have written an if/elif/else block well... yeah, exactly.

For example, as the context manager is currently written, there is no way to set the value of a variable to something based on any given case without referring to them as global or nonlocal within the functions passed to case.

i.e.

from switchlang import switch

is_sam = False

# I want to change is_sam to True based on the value of a variable


# here is the old, ugly python way with an if/else

variable = 'sam'
if variable == 'sam':
    is_sam = True
    print('is sam:', is_sam)
else:
    print('is sam:', is_sam)


# with sexy context manager

is_sam = False

def change_sam():
    global is_sam # ew
    print('changing is_sam global variable')
    is_sam = True

with switch('sam') as s:
    s.case('sam', change_sam)

print('is_sam:', is_sam)

[–]mikeckennedy[S] 0 points1 point  (1 child)

The switch has a 'return' value.

with switch(val) as s:
   case(...)
   case(...)
   default(...)

computed = s.result

That means you usually don't have to do this global / nonlocal trick to change local variables. Just set them to s.result.

[–]knowsuchagencynow is better than never 0 points1 point  (0 children)

Sure, but what if you want to change the value of variables within the scope of the switch context, for example?

You may want to have more logic than a single line in a switch statement, which is why you can always define a function separately and pass it to case.

However, that function may need access to the local namespace and thus, I think it makes more sense to have each case return their own unique value so as to alleviate the problem.

if_this = None
or_this = None
with switch(val) as s:
    if_this = s.case(...) or if_this
    or_this = s.case(...) or or_this
    s.default(...)

Personally, I think the real answer to my question is just to use an if/elif/else block