THIS Trick Is Kind Of Crazy In Python #code #programming #python

preview_player
Показать описание
This trick is kind of crazy in Python. #code #programming #python
Рекомендации по теме
Комментарии
Автор

This trick is always nice for quick and dirty math parsers because you can just look up the custom operator in the dictionary and automatically return the function to be populated by the relevant arguments

celestialowl
Автор

Unless there is more complex logic involved or variable numer of cases, just use if/match. Cool tricks and trying to be smart is what’a make codebases terrible.

Buffalo
Автор

You really taught me something new, I think this trick is really cool.❤

LEGEND-
Автор

Classes come with dicts of all the class methods including abstracted classes all the way down to default class methods, so you could use the same logic with ‘get’ but then using ‘self’ instead of defining your own dictionary:
getattr(self, “a”, self.default) # self is where you’re searching and self.default is the default function when no matching functions exist in your class

dimsum
Автор

Glad to see the method I've been using is posted by you. Feeling validated.
For functions with parameters, can use lambda and store the function in it, that way you can call it by passing values while executing.

terabhaininja
Автор

It's logical, since everything (functions included) is an object in Python - so you can store it in dict, pass it somwhere, and then just execute the ___call___ on it.

HOWEVER - it's generally a bad practice. Yes, it's a more concise way than if-else block, but as soon as you have to pass args/kwargs to the called func, and the number of functions in the dict start to multiply, you'll find yourself in a debugging hell.

Sometimes more code is the more readable solution

tomwin
Автор

Can also do inline ternary operators to compress that switch case into a single line of code. Alternatively, you can index the global variables:

globals()[‘a’]()

JordanMetroidManiac
Автор

This trick should be familiar to you. If you know Python for a long time. or any pl for that matter.

asagiai
Автор

Lol this is overall useful not just for functions. Here an example:

def compress(N1, N2, MODE):
compress_dict = {
0:(N1+N2),
1:(N1-N2),
2:(N1*N2),
3:(N1/N2),
4:(N1**N2),
5:(N1 / 100 ) * N2,
6:(sqrt(N1) if N1 == N2 else ValueError("N1 argument must be identical to argument N2!!!"))}
return compress_dict[MODE]

sphereguanzon
Автор

Nice trick, but you can simply download a code obfuscating tool and make your code even more unreadable and way harder to debug.

maswinkels
Автор

@Indently use match-case statement better.

El-HassanIbrahim
Автор

I haven't used Python in about six months now, but we had something like this where we wanted an enum where the function was only invoked if we accessed its value.

I think we did something like:

enum Producers(Callable[[], Int]):
FIRST(lambda: <complex int calculation here>)
SECOND(lambda: <memory intensive calculation here>)

and then we just did:
a = MyEnum.FIRST()

vorpal
Автор

This is almost how a switch works under the hood, just more overhead (but also more flexibility) since you are looking up the function in a map instead of just using a jump table

JanSoltan-wjhs
Автор

this' what I love about languages like Python when it comes to typing

keisanng
Автор

what if each function takes different arguments

snopz
Автор

"Strategy patern" is a valid solution here. This is bad.

psdmaniac
Автор

This was the way to go before they added the match keyword, indeed. 😅

DuniC
Автор

They're called Lookup table/dict/map/object depending on the language

geoafrikana
Автор

that's a very succinct-looking way to do that!

oliverli
Автор

I feel like this is useful for a very specific and niche use case, it’s kind of unreadable and complicated

JustinLietz
welcome to shbcf.ru