def test_args_handling(): def args_kwargs(a, b, c=None): return 1.0 * a / b * (c or 3) assert partial_apply(args_kwargs, 1)(2) == 1.0 / 2 * 3 assert partial_apply(args_kwargs, 1, 2, 1)() == 1.0 / 2 * 1
def test_kwargs_handling(): def args_kwargs(a, b, c=None): return 1.0 * a / b * (c or 3) assert partial_apply(args_kwargs, c=4)(1, 2) == 1.0 / 2 * 4 assert partial_apply(args_kwargs, 2, c=4)(6) == 2.0 / 6 * 4
def check_partial_apply(func, args=None, kwds=None, expected_source=None, expected_new_bindings=None): ''' Test that with given constants, optimized_ast transforms source to expected_source. It :expected_new_bindings: is given, we check that they are among new bindings returned by optimizer. ''' if args is None: args = tuple() if kwds is None: kwds = {} new_func = partial_apply(func, *args, **kwds) function = Function.from_object(new_func) if expected_source is not None: assert_ast_equal(function.tree, ast.parse(unindent(expected_source)).body[0]) if expected_new_bindings is not None: for k in expected_new_bindings: if k not in function.globals: print('Expected binding missing:', k) binding = function.globals[k] expected_binding = expected_new_bindings[k] # Python 3.2 defines equality for range objects incorrectly # (namely, the result is always False). # So we just test it manually. if sys.version_info < (3, 3) and isinstance(expected_binding, range): assert type(binding) == type(expected_binding) assert list(binding) == list(expected_binding) else: assert binding == expected_binding
def check_partial_apply(func, args=None, kwds=None, expected_source=None, expected_new_bindings=None): """ Test that with given constants, optimized_ast transforms source to expected_source. It :expected_new_bindings: is given, we check that they are among new bindings returned by optimizer. """ if args is None: args = tuple() if kwds is None: kwds = {} new_func = partial_apply(func, *args, **kwds) function = Function.from_object(new_func) if expected_source is not None: assert_ast_equal(function.tree, ast.parse(unindent(expected_source)).body[0]) if expected_new_bindings is not None: for k in expected_new_bindings: if k not in function.globals: print('Expected binding missing:', k) binding = function.globals[k] expected_binding = expected_new_bindings[k] assert binding == expected_binding
def check_partial_fn(base_fn, get_partial_kwargs, get_kwargs): ''' Check that partial evaluation of base_fn with partial_args gives the same result on args_list as functools.partial(base_fn, partial_args) ''' fn = partial_apply(base_fn, **get_partial_kwargs()) partial_fn = functools.partial(base_fn, **get_partial_kwargs()) # call two times to check for possible side-effects assert_func_equal_on(partial_fn, fn, **get_kwargs()) # first assert_func_equal_on(partial_fn, fn, **get_kwargs()) # second