Nov-01-2018, 08:08 PM
(This post was last modified: Nov-01-2018, 08:08 PM by Gribouillis.)
(Nov-01-2018, 06:22 PM)Skaperen Wrote: i don't understand this suggestion.Here is an example with a generic function
ddouble()
defined for three types in python 2 and 3from itertools import chain import sys if sys.version_info < (3,): from singledispatch import singledispatch else: from functools import singledispatch unicode = str @singledispatch def ddouble(item): raise NotImplementedError @ddouble.register(unicode) def _(s): return ''.join(x+x for x in s) @ddouble.register(bytearray) def _(s): return bytearray(chain.from_iterable(zip(*(s, s)))) @ddouble.register(bytes) def _(s): return bytes(ddouble(bytearray(s))) if __name__ == "__main__": data = b'Hello world!' udata = data.decode() print(repr(ddouble(data))) print(repr(ddouble(udata)))
Output:b'HHeelllloo wwoorrlldd'
'HHeelllloo wwoorrlldd'
(Nov-01-2018, 06:22 PM)Skaperen Wrote: i prefer to name functions based on API design before i codeThe types of a function's parameters are an important part of the API. You actually want function overloading. Generic functions are definitely a way.