Skip to content

Instantly share code, notes, and snippets.

@gidgid
Created February 24, 2021 19:39
Show Gist options
  • Save gidgid/0c919f74fb26540054292e39988df621 to your computer and use it in GitHub Desktop.
Save gidgid/0c919f74fb26540054292e39988df621 to your computer and use it in GitHub Desktop.
shows how we can overload methods via singledispatch
from functools import singledispatch
@singledispatch # 1
def to_json(inp): # 1
"""implementations in dispatched functions"""
@to_json.register # 2
def as_json_str(input_str: str) -> str: # 2
return f'"{input_str}"' # 4
@to_json.register # 3
def as_json_str(inputs: list) -> str: # 3
json_inputs = ", ".join(to_json(single_input) for single_input in inputs) # 4
return f"[{json_inputs}]" # 4
def test_to_json():
assert to_json("Hello world") == '"Hello world"' # 5
assert to_json(["a", "l", "i", "c", "e"]) == '["a", "l", "i", "c", "e"]' # 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment