Created
February 24, 2021 19:39
-
-
Save gidgid/0c919f74fb26540054292e39988df621 to your computer and use it in GitHub Desktop.
shows how we can overload methods via singledispatch
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 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