AVOID 'if-else' Hell In Python With THIS Simple Trick

preview_player
Показать описание
Avoid "if else" hell in #Python with this simple trick. #Shorts #Code
Рекомендации по теме
Комментарии
Автор

Match-case statement was introduced at Python version 3.10, works pretty well:)

bx_h
Автор

Code conciseness is a path to readability. It's never a goal by itself.

OL
Автор

Be careful when using this. It might be more concise but it is significantly more complicated to understand how the code works and what it does (especially if the code is more complicated). Rather than following the normal direct flow you have to look at a bunch of indirections.

mathijsfrank
Автор

guys no body will let you create else if hell or switch case hell in professional programming world. Your code have to follow the Open Closed Principle. And it will be much more easier to debug, faster run time (checking a lot of conditions like a lot is really slow's your code) and easy to extend. For everyone who is willing to work in tech field just get use to S.O.L.I.D principles

rrkatamakata
Автор

In 99% of "real world" (i.e. work/professionally related) cases the if cluster will be more legible and accessible for most developers.

And in terms of length it doesn't really need much more lines than what defining that dictionary requires. (And number of rows is not a detrimental metric when the tradeoff is clarity.)

So while it's clever and neat, it's very esoteric and as soon as you want to do something beyond a simple function call for one of the values you have to refactor it to an if cluster again. (Or use match/case if you're on 3.10+)

CurseTheVulgar
Автор

For those who are asking "what's the point of this technique?", here's your answer.

Event Handling architecture.

Dispatcher maps like these can use an event name string that comes in from some external messaging system. You can use the names of the events as the keys of a dictionary and write custom functions that do all the work you want when each specific event you care about is encountered. The function names for each even you want to handle are put into the value positions for each of the keys and which allows the values of the dictionary to be pointers available to be called later.

You can then pass in the name of the event from the message system into your dispatcher map, and allow your system to respond to the messages being intercepted in some dynamic way all without the need for ugly and unclean if/else statements.

thebluriam
Автор

This is also a great way of introducing first class functions as a concept.

catherinebernard
Автор

Sure, it's shorter, but has it any other advantages? I find elif ALOT more readable.
You just understand what you want do by reading it, whereas, if i, not a professionell dev, would use this and then stumble over this piece of Code a few weeks later id propably be lost.

clavix
Автор

This is super useful! I was not aware this was possible with dictionaries, the more you know!

happiestgameinexistence
Автор

If I saw this in production code I'd wonder what the hell went wrong

ThousandsOfPk
Автор

Just LOVE those little tidbits of code nuggets 😀

Converted that idea to JavaScript just for fun, since everything that CAN be written in JavaScript WILL eventually be written in JavaScript:

const v = "a value";

const myDict = {
"a value": one,
"a second value": two,
"a third value": three
};

const result = (myDict[v] || standard)();

(Had to rename 'default' to 'standard' since 'default' is a reserved word in JavaScript)

To be fair, switch statements have been introduced to both languages in the meantime, they make your codebase adhere to more conventional principles and hence might render it more read- and interpretable in the future 😁

christian-schubert
Автор

Nice, I did this old school method way back in 2014. Works great.

brothertyler
Автор

This is what I always do coming from javascript where object literals are the norms. It's nice that you can do something similar in python.

FS-yqef
Автор

this is one of my favorite alternatives to if/else statements in any programming language. really sad when a language doesnt support sticking references to functions in variables or arrays (though this is quite rare and is usually because it's some custom-made scripting language for a game)

Templarfreak
Автор

match var:
case 1:
first()
case 2:
second()
case 3:
third()
case _:
default()

dracokinerek
Автор

Slick. Up to this clip, I though that while Python was a little more compact than C or C++, I wasn't particularly impressed. This approach is worth getting excited about. Would really save a lot of time. Been slowly migrating from C++, gonna have to pick up the pace a bit. Thanks.

jimparsons
Автор

It is also in C#
Dictionary<int, Action> Dict = new()
Dict.Add(0, { Console.WriteLine("Test 1");})
Dict[0]();

AndrewX
Автор

SS: You did it! You make a anonymous function dict and kill the readability. A friend once did this, was funny at the beginning. One week in, and the problem was so big, we straight up start doing the project from the scratch.

selfspectrum
Автор

This method is called (multiple) dispatching, it's also referred to by its design pattern name, "the strategy pattern"

thebluriam
Автор

Interesting - these are the videos we need sir! Keep it up

matthewschuster