Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
byte types
#5
(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 3
from 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 code
The types of a function's parameters are an important part of the API. You actually want function overloading. Generic functions are definitely a way.
Reply


Messages In This Thread
byte types - by Skaperen - Oct-31-2018, 10:44 PM
RE: byte types - by wavic - Nov-01-2018, 05:03 AM
RE: byte types - by Gribouillis - Nov-01-2018, 09:18 AM
RE: byte types - by Skaperen - Nov-01-2018, 06:22 PM
RE: byte types - by Gribouillis - Nov-01-2018, 08:08 PM
RE: byte types - by Skaperen - Nov-02-2018, 12:05 AM
RE: byte types - by Gribouillis - Nov-02-2018, 05:45 AM
RE: byte types - by Skaperen - Nov-02-2018, 02:48 PM
RE: byte types - by wavic - Nov-02-2018, 06:06 PM
RE: byte types - by Skaperen - Nov-04-2018, 09:32 PM
RE: byte types - by ichabod801 - Nov-05-2018, 02:24 AM
RE: byte types - by Skaperen - Nov-06-2018, 12:55 AM
RE: byte types - by wavic - Nov-05-2018, 07:58 AM
RE: byte types - by Gribouillis - Nov-06-2018, 08:01 AM
RE: byte types - by Skaperen - Nov-07-2018, 04:03 AM
RE: byte types - by Gribouillis - Nov-07-2018, 09:19 PM
RE: byte types - by Skaperen - Nov-07-2018, 09:26 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020