Skip to content

Instantly share code, notes, and snippets.

@raeq
raeq / dict_05_bykey.py
Created August 2, 2020 12:13
Find all nested keys in a dict
import json
import requests
def get_values_by_key(dictionary: dict, key: str) -> dict:
"""get_values_by_key.
Args:
dictionary (dict): dictionary
key (str): key
@raeq
raeq / method_overloading.py
Last active May 2, 2021 21:30
method_overloading
from functools import singledispatchmethod
class Dog:
@singledispatchmethod
def bark(self, quality):
raise NotImplementedError
@bark.register
@raeq
raeq / which_dispatcher.py
Created May 2, 2021 12:38
Which Dispatcher
from functools import singledispatch
@singledispatch
def fancy_print(s):
raise NotImplementedError
@fancy_print.register(int)
def _ints(s):
@raeq
raeq / which_dispatcher.py
Created May 2, 2021 12:26
Which dispatcher will be called
from functools import singledispatch
@singledispatch
def fancy_print(s):
raise NotImplementedError
@fancy_print.register(int)
def _ints(s):
@raeq
raeq / with_overloading.py
Last active May 2, 2021 12:23
A simple overload using singledispatch
from functools import singledispatch
@singledispatch
def area(any_object):
raise NotImplementedError
@area.register(Circle)
def _(any_object):
return math.pi * (math.pow(any_object.radius, 2))
@raeq
raeq / with_overloading.py
Last active May 2, 2021 12:22
Worked example of overloading
import math
from functools import singledispatch
class Square:
length: int
def __init__(self, length=0):
self.length = length
from functools import singledispatch
@singledispatch
def area(any_object):
raise NotImplementedError
@area.register
def _(any_object: Circle):
return math.pi * (math.pow(any_object.radius, 2))
@raeq
raeq / example_04.py
Created May 2, 2021 11:08
Full code.
import math
class Square:
length: int
def __init__(self, length=0):
self.length = length
@raeq
raeq / example_03.py
Created May 2, 2021 11:06
Driver code
my_circle = Circle(6)
my_square = Square(12)
print(area(my_circle))
print(area(my_square))
@raeq
raeq / example_02.py
Created May 2, 2021 11:04
Calculate the area of circles or squares.
def area(any_object):
if isinstance(any_object, Circle):
return math.pi * (math.pow(any_object.radius, 2))
elif isinstance(any_object, Square):
return (math.pow(any_object.length, 2))