Python Forum

Full Version: converting a number from bytes to float and back
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
if given a number as str, int or float, you can add 1 to it and convert it back to the same type easily:
def inc(num):
    return type(num)(float(num)+1)
how can this be made to also work with bytes? note: it's OK for the return as str to have '.0' in it; it just needs to be str if str was given. i want this to also work if bytes is given; bytes is to be returned when bytes is given.
You can implement a decorator to force output type, e.g.



from functools import wraps
def retain_type(f):
    @wraps(f)
    def wrapper(inp):
        res = f(inp)
        if type(res) == type(inp):
            return res
        elif isinstance(res, str):
            return res.encode('utf-8')
        elif isinstance(res, bytes):
            return res.decode('utf-8')
        else:
            raise TypeError("Output type shoud be either bytes or str.")
    return wrapper
@retain_type
def inc(num):
    if isinstance(num, bytes):
        num = num.decode('utf-8')
    return type(num)(float(num)+1)
that blog is showing C code. why do you think i need to read that?