this post was submitted on 29 Aug 2023
23 points (100.0% liked)

Python

98 readers
1 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
top 5 comments
sorted by: hot top controversial new old
[–] sem@lemmy.ml 7 points 1 year ago (1 children)

To be honest, for me it looks as very strange pattern.. If one wants to have static container with functions, there is Enums or classes.

[–] Walnut356@programming.dev 2 points 1 year ago

It's most useful when you're using some data you already have as the dictionary key. A usecase i had for this was a binary file parser with 10 types of event markers. It was originally coded with if/elif, but performance was a pretty big consideration. Using the event markers as keys to a dictionary dispatch improved performance by about 15% and made the code significantly more readable.

[–] vox@sopuli.xyz 5 points 1 year ago* (last edited 1 year ago)

not unique to python.

function pointers and hashmaps exist in basically all languages

like in lua:

local table = {
  add = function(a, b) return a + b end
}
table["add"](4, 5)

JavaScript:

{
  add: (a, b) => a + b
}

Rust (using hashmaps with string keys is extremely inefficient tho, there are much better options here but whatever)

let map = HashMap::from([
   ("add", |a, b| a + b),
]);

//...

map["add"](1, 3);

[–] SubArcticTundra@lemmy.ml 3 points 1 year ago

I think a similar result might now be achievable with match statements

[–] sirdorius@programming.dev 2 points 1 year ago

This is fun to play around and basically what Python does under the hood to implement classes. In Python2 it was even more obvious that classes are just fancy wrappers around a dict called, unsurprisingly, __dict__.

class Foo: 
    def __init__(self):
        self.__dict__["instance_method"] = lambda: "instance_method"
        self.__dict__["shadowed_class_method"] = lambda: "shadowed_class_method_from_instance"
        

Foo.__dict__["class_method"] = lambda cls: "class_method"
Foo.__dict__["shadowed_class_method"] = lambda cls: "shadowed_class_method_from_class"

f = Foo()
f.__dict__["dynamic_instance_method"] = lambda: "dynamic_instance_method"

print f.instance_method()
print f.dynamic_instance_method()
print f.class_method()
print f.shadowed_class_method()

OUTPUT:
instance_method
dynamic_instance_method
class_method
shadowed_class_method_from_instance

Note: this won't work in Python3 because the class.__dict__ becomes immutable at some point after declaring it, but the attribute name resolution stays the same. And it gets more interesting once you throw inheritance into the mix.