Skip to content

Instantly share code, notes, and snippets.

@1stvamp
Last active December 22, 2015 03:49
Show Gist options
  • Save 1stvamp/6412698 to your computer and use it in GitHub Desktop.
Save 1stvamp/6412698 to your computer and use it in GitHub Desktop.
Alternatives to the callable hashmap pattern in Python
"""This is the most common form of implementing a callable map in Python,
using a dict that names each callable.
However as you can it means effectively defining names in several places
when you need more than a simple lambda for your callable, due to Python
not having first class anonymous functions.
example: python 1_dict_hashmap.py complex
"""
import sys
def complex():
return 'foo'
def bar():
return 'foo'
map = {
'simple': lambda: return 'foo'
'complex': complex,
'bar': bar
}
arg = sys.argv[1]
print(map[arg]())
"""One alternative to using dicts for callable maps is to treat
the module itself as a dict using the ``globals()`` function
which returns a dict with all the current modules properties.
As you can guess this might not be ideal if you had other methods
and properties defined in the same namespace as the map however,
as you might accidentally expose these when you didn't mean to.
example: python 2_globals_hashmap.py bar
"""
import sys
simple = lambda: return 'foo'
def complex():
return 'foo'
def bar():
return 'foo'
arg = sys.argv[1]
print(globals()[arg]())
"""My favourite method is to use a good ol' class with the lesser
used ``@staticmethod`` decorator, allowing us to access the class
as a map with ``getattr()``, and call anything defined inside the
map class's scope.
example: python 3_class_hashmap.py foo
"""
import sys
class Map:
simple = lambda: return 'foo'
@staticmethod
def complex():
return 'foo'
@staticmethod
def bar():
return 'foo'
arg = sys.argv[1]
print(getattr(Map, arg)())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment