functools.singledispatch
functools library includes the singledispatch()
decorator. It let'slets you provide a generic function, but provide special cases based on the type of the first argument.
import functools
import random
@functools.singledispatch
def shuffle(arg, order):
"""this is the generic shuffle function"""
lst = list(arg)
return type(arg)(lst[i] for i in order)
@shuffle.register(dict)
def _(arg, order):
"""this is shuffle() specialized to handle dicts"""
item = list(arg.items())
return dict(item[i] for i in order)
def ordered_shuffle(*args):
min_length = min(map(len, args))
indices = random.sample(range(min_length), min_length)
return [shuffle(arg, indices) for arg in args]
Usage:
a = (1, 2, {3: 4}, 5)
b = [(5,6), [7,8], [9,0], [1,2]]
c = {'arrow': 5, 'knee': 'guard', 0: ('x',2)}
ordered_shuffle(a, b, c)
Output:
[({3: 4}, 1, 2),
[[9, 0], (5, 6), [7, 8]],
{0: ('x', 2), 'arrow': 5, 'knee': 'guard'}]