CodyKochmann
10/14/2016 - 3:40 PM

Control what functions can return

Control what functions can return

class output_type(object):
    # control how functions output data
    # by: Cody Kochmann
    def __init__(self, *specified_type):
        assert all(type(list) is type(i) for i in specified_type), "output type must be a <type 'type'>"
        self.specified_type = specified_type[0]
    def __call__(self,f):
        def wrapper(*args, **kwargs):
            out = f(*args, **kwargs)
            assert isinstance(out, self.specified_type),\
                "{} has to return a {} instead of a {}".format(
                    f.__name__,
                    self.specified_type.__name__,
                    type(out).__name__)
            return out
        return wrapper

@output_type(float)
def t():
    return 0.0

t()
class output_rule(object):
    # control how functions output data
    # by: Cody Kochmann
    def __init__(self, rule, description=''):
        assert type(rule) is type(lambda:0), "output_rule is missing its 'rule' argument"
        assert isinstance(description, str), "output_rule's description needs to be a string"
        self.rule = rule
        self.description = description
    def __call__(self,f):
        def wrapper(*args, **kwargs):
            out = f(*args, **kwargs)
            assert self.rule(out), self.description
            return out
        return wrapper

@output_rule(lambda out: out > 1, "output needs to be more than 1")
@output_rule(lambda out: out%2 == 0, "output needs to be even") # this one overwrites the first :(
def t():
    return 2.0

t()