Last active
March 17, 2017 07:57
-
-
Save soaxelbrooke/8977af48bbfabc342b1f76539316d8da to your computer and use it in GitHub Desktop.
A callable dictionary useful for functional programming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional, Hashable, TypeVar | |
class CallableDict(dict): | |
V = TypeVar('V') | |
""" A callable dictionary useful for functional programming """ | |
def __call__(self, key: Hashable, default: Optional[V]=None) -> Optional[V]: | |
return self.get(key, default) | |
label_nums = CallableDict({ | |
'app.launch': 0, | |
'app.exit': 1, | |
'app.pause': 2, | |
'app.resume': 3, | |
}) | |
print(label_nums['app.pause']) | |
print(list(map(label_nums, [ | |
'app.launch', 'app.pause', 'app.resume', 'app.exit', 'app.launch', 'app.pause', 'app.exit', | |
'app.launch', 'app.exit', | |
]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python has a native syntax to do functional processing on anything: list comprehensions.
Is simply:
Benefits:
Although most Python dev would probably reformat it and provide a default value this way:
Use Python the way it's intended to be.