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', | |
]))) |
Python has a native syntax to do functional processing on anything: list comprehensions.
print(list(map(label_nums, [
'app.launch', 'app.pause', 'app.resume', 'app.exit', 'app.launch', 'app.pause', 'app.exit',
'app.launch', 'app.exit',
])))
Is simply:
print([label_nums[key] for key in [
'app.launch', 'app.pause', 'app.resume', 'app.exit', 'app.launch', 'app.pause', 'app.exit',
'app.launch', 'app.exit',
]])
Benefits:
- no side effects
- clear intents
- native idiomatic syntax
- can be turned into a generator if you want to
Although most Python dev would probably reformat it and provide a default value this way:
events = [
'app.launch',
'app.pause',
'app.resume',
'app.exit',
'app.launch',
'app.pause',
'app.exit',
'app.launch',
'app.exit',
]
print([label_nums.get(event, 'default') for event in events)]
Use Python the way it's intended to be.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
class CallableDict(dict):
slots = ()
call = dict.get