Skip to content

Instantly share code, notes, and snippets.

@micseydel
Created February 7, 2020 20:43
Show Gist options
  • Save micseydel/9c169549f10fc6fa9aa7ae81bb29e06b to your computer and use it in GitHub Desktop.
Save micseydel/9c169549f10fc6fa9aa7ae81bb29e06b to your computer and use it in GitHub Desktop.
from typing import List, Optional
def get_array_from_dict(d: dict, key: str, default: List[object] = list()) -> List[object]:
"""Gets an array from a dict. Casts the type to List. Allows defaults to be set - no errors thrown."""
return d.get(key, default)
foo = get_array_from_dict({}, "foo")
bar = get_array_from_dict({}, "bar")
foo.append(1)
print("get_array_from_dict")
print(foo, bar)
# but there's a way around this...
def get_list_from_dict(d: dict, key: str, default: Optional[List[object]] = None) -> List[object]:
"""Gets an array from a dict. Casts the type to List. Allows defaults to be set - no errors thrown."""
result = d.get(key)
if result is None:
result = []
return result
foo = get_list_from_dict({}, "foo")
bar = get_list_from_dict({}, "bar")
foo.append(1)
print("\nget_list_from_dict")
print(foo, bar)
"""
output:
get_array_from_dict
[1] [1]
get_list_from_dict
[1] []
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment