• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utils.raises函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中toolz.utils.raises函数的典型用法代码示例。如果您正苦于以下问题:Python raises函数的具体用法?Python raises怎么用?Python raises使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了raises函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_curry_comparable

def test_curry_comparable():
    def foo(a, b, c=1):
        return a + b + c
    f1 = curry(foo, 1, c=2)
    f2 = curry(foo, 1, c=2)
    g1 = curry(foo, 1, c=3)
    h1 = curry(foo, c=2)
    h2 = h1(c=2)
    h3 = h1()
    assert f1 == f2
    assert not (f1 != f2)
    assert f1 != g1
    assert not (f1 == g1)
    assert f1 != h1
    assert h1 == h2
    assert h1 == h3

    # test function comparison works
    def bar(a, b, c=1):
        return a + b + c
    b1 = curry(bar, 1, c=2)
    assert b1 != f1

    assert set([f1, f2, g1, h1, h2, h3, b1, b1()]) == set([f1, g1, h1, b1])

    # test unhashable input
    unhash1 = curry(foo, [])
    assert raises(TypeError, lambda: hash(unhash1))
    unhash2 = curry(foo, c=[])
    assert raises(TypeError, lambda: hash(unhash2))
开发者ID:karansag,项目名称:toolz,代码行数:30,代码来源:test_functoolz.py


示例2: test_excepts

def test_excepts():
    # These are descriptors, make sure this works correctly.
    assert excepts.__name__ == 'excepts'
    assert excepts.__doc__.startswith(
        'A wrapper around a function to catch exceptions and\n'
        '    dispatch to a handler.\n'
    )

    def idx(a):
        """idx docstring
        """
        return [1, 2].index(a)

    def handler(e):
        """handler docstring
        """
        assert isinstance(e, ValueError)
        return -1

    excepting = excepts(ValueError, idx, handler)
    assert excepting(1) == 0
    assert excepting(2) == 1
    assert excepting(3) == -1

    assert excepting.__name__ == 'idx_excepting_ValueError'
    assert 'idx docstring' in excepting.__doc__
    assert 'ValueError' in excepting.__doc__
    assert 'handler docstring' in excepting.__doc__

    def getzero(a):
        """getzero docstring
        """
        return a[0]

    excepting = excepts((IndexError, KeyError), getzero)
    assert excepting([]) is None
    assert excepting([1]) == 1
    assert excepting({}) is None
    assert excepting({0: 1}) == 1

    assert excepting.__name__ == 'getzero_excepting_IndexError_or_KeyError'
    assert 'getzero docstring' in excepting.__doc__
    assert 'return_none' in excepting.__doc__
    assert 'Returns None' in excepting.__doc__

    def raise_(a):
        """A function that raises an instance of the exception type given.
        """
        raise a()

    excepting = excepts((ValueError, KeyError), raise_)
    assert excepting(ValueError) is None
    assert excepting(KeyError) is None
    assert raises(TypeError, lambda: excepting(TypeError))
    assert raises(NotImplementedError, lambda: excepting(NotImplementedError))

    excepting = excepts(object(), object(), object())
    assert excepting.__name__ == 'excepting'
    assert excepting.__doc__ == excepts.__doc__
开发者ID:AndrewWalker,项目名称:toolz,代码行数:59,代码来源:test_functoolz.py


示例3: test_curry_attributes_readonly

def test_curry_attributes_readonly():
    def foo(a, b, c=1):
        return a + b + c

    f = curry(foo, 1, c=2)
    assert raises(AttributeError, lambda: setattr(f, 'args', (2,)))
    assert raises(AttributeError, lambda: setattr(f, 'keywords', {'c': 3}))
    assert raises(AttributeError, lambda: setattr(f, 'func', f))
开发者ID:karansag,项目名称:toolz,代码行数:8,代码来源:test_functoolz.py


示例4: test_nth

def test_nth():
    assert nth(2, 'ABCDE') == 'C'
    assert nth(2, iter('ABCDE')) == 'C'
    assert nth(1, (3, 2, 1)) == 2
    assert nth(0, {'foo': 'bar'}) == 'foo'
    assert raises(StopIteration, lambda: nth(10, {10: 'foo'}))
    assert nth(-2, 'ABCDE') == 'D'
    assert raises(ValueError, lambda: nth(-2, iter('ABCDE')))
开发者ID:caioaao,项目名称:toolz,代码行数:8,代码来源:test_itertoolz.py


示例5: test_get

def test_get():
    assert get(1, 'ABCDE') == 'B'
    assert list(get([1, 3], 'ABCDE')) == list('BD')
    assert get('a', {'a': 1, 'b': 2, 'c': 3}) == 1
    assert get(['a', 'b'], {'a': 1, 'b': 2, 'c': 3}) == (1, 2)

    assert get('foo', {}, default='bar') == 'bar'

    assert raises(IndexError, lambda: get(10, 'ABC'))
    assert raises(KeyError, lambda: get(10, {'a': 1}))
开发者ID:JNRowe,项目名称:toolz,代码行数:10,代码来源:test_core.py


示例6: test_curry_passes_errors

def test_curry_passes_errors():
    @curry
    def f(a, b):
        if not isinstance(a, int):
            raise TypeError()
        return a + b

    assert f(1, 2) == 3
    assert raises(TypeError, lambda: f('1', 2))
    assert raises(TypeError, lambda: f('1')(2))
    assert raises(TypeError, lambda: f(1, 2, 3))
开发者ID:karansag,项目名称:toolz,代码行数:11,代码来源:test_functoolz.py


示例7: test_curry_simple

def test_curry_simple():
    cmul = curry(mul)
    double = cmul(2)
    assert callable(double)
    assert double(10) == 20
    assert repr(cmul) == repr(mul)

    cmap = curry(map)
    assert list(cmap(inc)([1, 2, 3])) == [2, 3, 4]

    assert raises(TypeError, lambda: curry())
    assert raises(TypeError, lambda: curry({1: 2}))
开发者ID:AndrewWalker,项目名称:toolz,代码行数:12,代码来源:test_functoolz.py


示例8: test_get

def test_get():
    assert get(1, "ABCDE") == "B"
    assert list(get([1, 3], "ABCDE")) == list("BD")
    assert get("a", {"a": 1, "b": 2, "c": 3}) == 1
    assert get(["a", "b"], {"a": 1, "b": 2, "c": 3}) == (1, 2)

    assert get("foo", {}, default="bar") == "bar"
    assert get({}, [1, 2, 3], default="bar") == "bar"
    assert get([0, 2], "AB", "C") == ("A", "C")

    assert raises(IndexError, lambda: get(10, "ABC"))
    assert raises(KeyError, lambda: get(10, {"a": 1}))
    assert raises(TypeError, lambda: get({}, [1, 2, 3]))
开发者ID:joyrexus,项目名称:toolz,代码行数:13,代码来源:test_core.py


示例9: test_pluck

def test_pluck():
    assert list(pluck(0, [[0, 1], [2, 3], [4, 5]])) == [0, 2, 4]
    assert list(pluck([0, 1], [[0, 1, 2], [3, 4, 5]])) == [(0, 1), (3, 4)]
    assert list(pluck(1, [[0], [0, 1]], None)) == [None, 1]

    data = [{'id': 1, 'name': 'cheese'}, {'id': 2, 'name': 'pies', 'price': 1}]
    assert list(pluck('id', data)) == [1, 2]
    assert list(pluck('price', data, None)) == [None, 1]
    assert list(pluck(['id', 'name'], data)) == [(1, 'cheese'), (2, 'pies')]
    assert list(pluck(['price', 'other'], data, None)) == [(None, None),
                                                           (1, None)]

    assert raises(IndexError, lambda: list(pluck(1, [[0]])))
    assert raises(KeyError, lambda: list(pluck('name', [{'id': 1}])))
开发者ID:karansag,项目名称:toolz,代码行数:14,代码来源:test_itertoolz.py


示例10: test_curry_call

def test_curry_call():
    @curry
    def add(x, y):
        return x + y
    assert raises(TypeError, lambda: add.call(1))
    assert add(1)(2) == add.call(1, 2)
    assert add(1)(2) == add(1).call(2)
开发者ID:Michael2011,项目名称:code-note,代码行数:7,代码来源:test_functoolz.py


示例11: test_curry_kwargs

def test_curry_kwargs():
    def f(a, b, c=10):
        return (a + b) * c

    f = curry(f)
    assert f(1, 2, 3) == 9
    assert f(1)(2, 3) == 9
    assert f(1, 2) == 30
    assert f(1, c=3)(2) == 9
    assert f(c=3)(1, 2) == 9

    def g(a=1, b=10, c=0):
        return a + b + c

    cg = curry(g, b=2)
    assert cg() == 3
    assert cg(b=3) == 4
    assert cg(a=0) == 2
    assert cg(a=0, b=1) == 1
    assert cg(0) == 2  # pass "a" as arg, not kwarg
    assert raises(TypeError, lambda: cg(1, 2))  # pass "b" as arg AND kwarg

    def h(x, func=int):
        return func(x)

    if platform.python_implementation() != 'PyPy'\
            or platform.python_version_tuple()[0] != '3':  # Bug on PyPy3<2.5
        # __init__ must not pick func as positional arg
        assert curry(h)(0.0) == 0
        assert curry(h)(func=str)(0.0) == '0.0'
        assert curry(h, func=str)(0.0) == '0.0'
开发者ID:AndrewWalker,项目名称:toolz,代码行数:31,代码来源:test_functoolz.py


示例12: test_get

def test_get():
    assert get(1, 'ABCDE') == 'B'
    assert list(get([1, 3], 'ABCDE')) == list('BD')
    assert get('a', {'a': 1, 'b': 2, 'c': 3}) == 1
    assert get(['a', 'b'], {'a': 1, 'b': 2, 'c': 3}) == (1, 2)

    assert get('foo', {}, default='bar') == 'bar'
    assert get({}, [1, 2, 3], default='bar') == 'bar'
    assert get([0, 2], 'AB', 'C') == ('A', 'C')

    assert get([0], 'AB') == ('A',)

    assert raises(IndexError, lambda: get(10, 'ABC'))
    assert raises(KeyError, lambda: get(10, {'a': 1}))
    assert raises(TypeError, lambda: get({}, [1, 2, 3]))
    assert raises(TypeError, lambda: get([1, 2, 3], 1, None))
开发者ID:B-Rich,项目名称:toolz,代码行数:16,代码来源:test_itertoolz.py


示例13: test_peek

def test_peek():
    alist = ["Alice", "Bob", "Carol"]
    element, blist = peek(alist)
    element == alist[0]
    assert list(blist) == alist

    assert raises(StopIteration, lambda: peek([]))
开发者ID:caioaao,项目名称:toolz,代码行数:7,代码来源:test_itertoolz.py


示例14: test_factory

def test_factory():
    assert merge(defaultdict(int, {1: 2}), {2: 3}) == {1: 2, 2: 3}
    assert (merge(defaultdict(int, {1: 2}), {2: 3},
                  factory=lambda: defaultdict(int)) ==
            defaultdict(int, {1: 2, 2: 3}))
    assert not (merge(defaultdict(int, {1: 2}), {2: 3},
                      factory=lambda: defaultdict(int)) == {1: 2, 2: 3})
    assert raises(TypeError, lambda: merge({1: 2}, {2: 3}, factoryy=dict))
开发者ID:cpcloud,项目名称:toolz,代码行数:8,代码来源:test_dicttoolz.py


示例15: test_diff

def test_diff():
    assert raises(TypeError, lambda: list(diff()))
    assert raises(TypeError, lambda: list(diff([1, 2])))
    assert raises(TypeError, lambda: list(diff([1, 2], 3)))
    assert list(diff([1, 2], (1, 2), iter([1, 2]))) == []
    assert list(diff([1, 2, 3], (1, 10, 3), iter([1, 2, 10]))) == [
        (2, 10, 2), (3, 3, 10)]
    assert list(diff([1, 2], [10])) == [(1, 10)]
    assert list(diff([1, 2], [10], default=None)) == [(1, 10), (2, None)]
    # non-variadic usage
    assert raises(TypeError, lambda: list(diff([])))
    assert raises(TypeError, lambda: list(diff([[]])))
    assert raises(TypeError, lambda: list(diff([[1, 2]])))
    assert raises(TypeError, lambda: list(diff([[1, 2], 3])))
    assert list(diff([(1, 2), (1, 3)])) == [(2, 3)]

    data1 = [{'cost': 1, 'currency': 'dollar'},
             {'cost': 2, 'currency': 'dollar'}]

    data2 = [{'cost': 100, 'currency': 'yen'},
             {'cost': 300, 'currency': 'yen'}]

    conversions = {'dollar': 1, 'yen': 0.01}

    def indollars(item):
        return conversions[item['currency']] * item['cost']

    list(diff(data1, data2, key=indollars)) == [
        ({'cost': 2, 'currency': 'dollar'}, {'cost': 300, 'currency': 'yen'})]
开发者ID:caioaao,项目名称:toolz,代码行数:29,代码来源:test_itertoolz.py


示例16: test_factory

 def test_factory(self):
     D, kw = self.D, self.kw
     assert merge(defaultdict(int, D({1: 2})), D({2: 3})) == {1: 2, 2: 3}
     assert (merge(defaultdict(int, D({1: 2})), D({2: 3}),
                   factory=lambda: defaultdict(int)) ==
             defaultdict(int, D({1: 2, 2: 3})))
     assert not (merge(defaultdict(int, D({1: 2})), D({2: 3}),
                       factory=lambda: defaultdict(int)) == {1: 2, 2: 3})
     assert raises(TypeError, lambda: merge(D({1: 2}), D({2: 3}), factoryy=dict))
开发者ID:ZachPhillipsGary,项目名称:CS200-NLP-ANNsProject,代码行数:9,代码来源:test_dicttoolz.py


示例17: test_get_in

def test_get_in():
    # Test object support:
    o = C()
    a = C()
    a.b = 1
    o.a = a
    assert get_in(['a', 'b'], o) == 1
    assert get_in(['a', 'b', 'c'], o, 2) == 2
    assert raises(AttributeError,
                  lambda: get_in(['a', 'b', 'c'], o, no_default=True))
开发者ID:berrytj,项目名称:toolz,代码行数:10,代码来源:test_dicttoolz.py


示例18: test_update_in

def test_update_in():
    assert update_in({"a": 0}, ["a"], inc) == {"a": 1}
    assert update_in({"a": 0, "b": 1}, ["b"], str) == {"a": 0, "b": "1"}
    assert (update_in({"t": 1, "v": {"a": 0}}, ["v", "a"], inc) ==
            {"t": 1, "v": {"a": 1}})
    # Handle one missing key.
    assert update_in({}, ["z"], str, None) == {"z": "None"}
    assert update_in({}, ["z"], inc, 0) == {"z": 1}
    assert update_in({}, ["z"], lambda x: x+"ar", default="b") == {"z": "bar"}
    # Same semantics as Clojure for multiple missing keys, ie. recursively
    # create nested empty dictionaries to the depth specified by the
    # keys with the innermost value set to f(default).
    assert update_in({}, [0, 1], inc, default=-1) == {0: {1: 0}}
    assert update_in({}, [0, 1], str, default=100) == {0: {1: "100"}}
    assert (update_in({"foo": "bar", 1: 50}, ["d", 1, 0], str, 20) ==
            {"foo": "bar", 1: 50, "d": {1: {0: "20"}}})
    # Verify immutability:
    d = {'x': 1}
    oldd = d
    update_in(d, ['x'], inc)
    assert d is oldd

    # Test object support:
    c = C()
    c.a = 0
    assert update_in(c, ["a"], inc).__dict__ == {"a": 1}
    c = C()
    c.a = 0
    c.b = 1
    assert update_in(c, ["b"], str).__dict__ == {"a": 0, "b": "1"}
    v = C()
    v.a = 0
    c = C()
    c.t = 1
    c.v = v
    assert update_in(c, ["v", "a"], inc).v.__dict__ == {"a": 1}

    # Handle one missing key.
    c = C()
    assert update_in(c, ["z"], str, None).__dict__ == {"z": "None"}
    assert update_in(c, ["z"], inc, 0).__dict__ == {"z": 1}
    assert update_in(c, ["z"], lambda x: x + "ar",
                         default="b").__dict__ == {"z": "bar"}

    # Allow AttributeError to be thrown if more than one missing key,
    # because we don't know what type of object to create for nesting.
    assert raises(AttributeError,
                  lambda: update_in(c, ["y", "z"], inc, default=0))

    # Verify immutability:
    o = C()
    o.x = 1
    update_in(o, ['x'], inc)
    assert o.x == 1
开发者ID:berrytj,项目名称:toolz,代码行数:54,代码来源:test_dicttoolz.py


示例19: test_memoize

def test_memoize():
    fn_calls = [0]  # Storage for side effects

    def f(x, y):
        """ A docstring """
        fn_calls[0] += 1
        return x + y
    mf = memoize(f)

    assert mf(2, 3) == mf(2, 3)
    assert fn_calls == [1]  # function was only called once
    assert mf.__doc__ == f.__doc__
    assert raises(TypeError, lambda: mf(1, {}))
开发者ID:karansag,项目名称:toolz,代码行数:13,代码来源:test_functoolz.py


示例20: test_make_func

def test_make_func():
    f = make_func('')
    assert raises(ValueError, lambda: f())
    assert raises(TypeError, lambda: f(1))

    f = make_func('', raise_if_called=False)
    assert f()
    assert raises(TypeError, lambda: f(1))

    f = make_func('x, y=1', raise_if_called=False)
    assert f(1)
    assert f(x=1)
    assert f(1, 2)
    assert f(x=1, y=2)
    assert raises(TypeError, lambda: f(1, 2, 3))

    f = make_func('(x, y=1)', raise_if_called=False)
    assert f(1)
    assert f(x=1)
    assert f(1, 2)
    assert f(x=1, y=2)
    assert raises(TypeError, lambda: f(1, 2, 3))
开发者ID:steven-cutting,项目名称:toolz,代码行数:22,代码来源:test_inspect_args.py



注:本文中的toolz.utils.raises函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ai.ToonBarrier类代码示例发布时间:2022-05-27
下一篇:
Python itertoolz.join函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap