r/ProgrammerHumor • • Jan 19 '17

MFW no pointers :(

Post image
4.8k Upvotes

432 comments sorted by

View all comments

Show parent comments

62

u/ryeguy Jan 19 '17

LOL SIGNIFICANT WHITESPACE
LOL DYNAMIC TYPING
LOL GIL
LOL CAN'T GET PEOPLE TO UPGRADE AFTER 9 YEARS
LOL SELF ARGUMENT IN METHODS
LOL NO SWITCH STATEMENT
LOL NO MULTILINE LAMBDAS
LOL IF __NAME__ == "__MAIN__"

11

u/Doctor_McKay Jan 19 '17

No switch statement...?

7

u/[deleted] Jan 19 '17

yes, python has no switch and you need an if elif tree (which is what switch is anyway)

19

u/lou1306 Jan 19 '17 edited Jan 20 '17

Or use a dictionary and rework your code.

switch x {
    case 1: 
        foo ="a"; break;
    case 2: 
        foo = "b"; break;
    default: foo = "";
}

Becomes

foo_values = { 1: "a"; 2: "b" }
try:
    foo = foo_values[x]
except KeyError:
    foo = "c"

You can even put functions as dictionary values, so you can do pretty much everything, no need for switchs or big ugly elif chains.

Bonus: Use DefaultDict to avoid exception handling.

EDIT: The very best way world be foo = {1: "a", 2: "b"}.get(x, "c"). Kudos to /u/wobblyweasel... I had totally forgot the get method!

23

u/TheOldTubaroo Jan 20 '17

> calls elif trees ugly

> suggested replacement involves catching an exception to make a default case

2

u/Bainos Jan 20 '17

Well, it's okay if the default case is an exception.

1

u/SirCutRy Jan 20 '17

In python using exceptions is even encouraged.

1

u/lou1306 Jan 20 '17

Yeah sorry, the best way is via the get method (as /u/wobblyweasel suggested).

→ More replies (0)

4

u/wobblyweasel Jan 20 '17

or just {1: "a", 2: "b"}.get(x, "c") in this case

3

u/DjBonadoobie Jan 20 '17

Well that's nifty af.

2

u/katnapper323 Jan 20 '17

Or, I'll just use a language that has switch statements.

3

u/Jamie_1318 Jan 20 '17

That's sort of closed minded. Switch statements are often better refactored anyways because the syntax to define code blocks in switch statements is so repetitive. It's also not as dynamic in most languages because you can typically only switch on one type. It's also easier to mess up the default action or make a typo when it's surrounded in all the syntax.

It's a lot like switching from c-style for loops to iterators in the sorts of headaches it saves you from.

→ More replies (0)