Conversation

Mostly you shouldn't subclass built-in types. But if you do, dict subclasses can define __missing__: it's called when a key is missing. Instead of hiding a dict in a function as a cache, how about hiding a function in a dict!? A Fibonacci dictionary:

3
1
0

@nedbat I've been told that subclassing collections.UserDict would be better, as dict itself may optimize away and miss calling some dunder methods sometimes.

0
0
0
fib = {0 => 1, 1 => 1}.tap { _1.default_proc = ->(h,k) { h[k] = h[k-1] + h[k-2] }}
fib[10]  # 89
fib[100] # 573147844013817084101
fib[200] # 453973694165307953197296969697410619233826
fib.size # 201


RE: https://hachyderm.io/@nedbat/112569940156009404
0
0
5