test_functoolz.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import inspect
  2. import cytoolz
  3. from cytoolz.functoolz import (thread_first, thread_last, memoize, curry,
  4. compose, compose_left, pipe, complement, do, juxt,
  5. flip, excepts, apply)
  6. from cytoolz.compatibility import PY3
  7. from operator import add, mul, itemgetter
  8. from cytoolz.utils import raises
  9. from functools import partial
  10. def iseven(x):
  11. return x % 2 == 0
  12. def isodd(x):
  13. return x % 2 == 1
  14. def inc(x):
  15. return x + 1
  16. def double(x):
  17. return 2 * x
  18. class AlwaysEquals(object):
  19. """useful to test correct __eq__ implementation of other objects"""
  20. def __eq__(self, other):
  21. return True
  22. def __ne__(self, other):
  23. return False
  24. class NeverEquals(object):
  25. """useful to test correct __eq__ implementation of other objects"""
  26. def __eq__(self, other):
  27. return False
  28. def __ne__(self, other):
  29. return True
  30. def test_apply():
  31. assert apply(double, 5) == 10
  32. assert tuple(map(apply, [double, inc, double], [10, 500, 8000])) == (20, 501, 16000)
  33. assert raises(TypeError, apply)
  34. def test_thread_first():
  35. assert thread_first(2) == 2
  36. assert thread_first(2, inc) == 3
  37. assert thread_first(2, inc, inc) == 4
  38. assert thread_first(2, double, inc) == 5
  39. assert thread_first(2, (add, 5), double) == 14
  40. def test_thread_last():
  41. assert list(thread_last([1, 2, 3], (map, inc), (filter, iseven))) == [2, 4]
  42. assert list(thread_last([1, 2, 3], (map, inc), (filter, isodd))) == [3]
  43. assert thread_last(2, (add, 5), double) == 14
  44. def test_memoize():
  45. fn_calls = [0] # Storage for side effects
  46. def f(x, y):
  47. """ A docstring """
  48. fn_calls[0] += 1
  49. return x + y
  50. mf = memoize(f)
  51. assert mf(2, 3) is mf(2, 3)
  52. assert fn_calls == [1] # function was only called once
  53. assert mf.__doc__ == f.__doc__
  54. assert raises(TypeError, lambda: mf(1, {}))
  55. def test_memoize_kwargs():
  56. fn_calls = [0] # Storage for side effects
  57. def f(x, y=0):
  58. return x + y
  59. mf = memoize(f)
  60. assert mf(1) == f(1)
  61. assert mf(1, 2) == f(1, 2)
  62. assert mf(1, y=2) == f(1, y=2)
  63. assert mf(1, y=3) == f(1, y=3)
  64. def test_memoize_curried():
  65. @curry
  66. def f(x, y=0):
  67. return x + y
  68. f2 = f(y=1)
  69. fm2 = memoize(f2)
  70. assert fm2(3) == f2(3)
  71. assert fm2(3) == f2(3)
  72. def test_memoize_partial():
  73. def f(x, y=0):
  74. return x + y
  75. f2 = partial(f, y=1)
  76. fm2 = memoize(f2)
  77. assert fm2(3) == f2(3)
  78. assert fm2(3) == f2(3)
  79. def test_memoize_key_signature():
  80. # Single argument should not be tupled as a key. No keywords.
  81. mf = memoize(lambda x: False, cache={1: True})
  82. assert mf(1) is True
  83. assert mf(2) is False
  84. # Single argument must be tupled if signature has varargs. No keywords.
  85. mf = memoize(lambda x, *args: False, cache={(1,): True, (1, 2): 2})
  86. assert mf(1) is True
  87. assert mf(2) is False
  88. assert mf(1, 1) is False
  89. assert mf(1, 2) == 2
  90. assert mf((1, 2)) is False
  91. # More than one argument is always tupled. No keywords.
  92. mf = memoize(lambda x, y: False, cache={(1, 2): True})
  93. assert mf(1, 2) is True
  94. assert mf(1, 3) is False
  95. assert raises(TypeError, lambda: mf((1, 2)))
  96. # Nullary function (no inputs) uses empty tuple as the key
  97. mf = memoize(lambda: False, cache={(): True})
  98. assert mf() is True
  99. # Single argument must be tupled if there are keyword arguments, because
  100. # keyword arguments may be passed as unnamed args.
  101. mf = memoize(lambda x, y=0: False,
  102. cache={((1,), frozenset((('y', 2),))): 2,
  103. ((1, 2), None): 3})
  104. assert mf(1, y=2) == 2
  105. assert mf(1, 2) == 3
  106. assert mf(2, y=2) is False
  107. assert mf(2, 2) is False
  108. assert mf(1) is False
  109. assert mf((1, 2)) is False
  110. # Keyword-only signatures must still have an "args" tuple.
  111. mf = memoize(lambda x=0: False, cache={(None, frozenset((('x', 1),))): 1,
  112. ((1,), None): 2})
  113. assert mf() is False
  114. assert mf(x=1) == 1
  115. assert mf(1) == 2
  116. def test_memoize_curry_cache():
  117. @memoize(cache={1: True})
  118. def f(x):
  119. return False
  120. assert f(1) is True
  121. assert f(2) is False
  122. def test_memoize_key():
  123. @memoize(key=lambda args, kwargs: args[0])
  124. def f(x, y, *args, **kwargs):
  125. return x + y
  126. assert f(1, 2) == 3
  127. assert f(1, 3) == 3
  128. def test_memoize_wrapped():
  129. def foo():
  130. """
  131. Docstring
  132. """
  133. pass
  134. memoized_foo = memoize(foo)
  135. assert memoized_foo.__wrapped__ is foo
  136. def test_curry_simple():
  137. cmul = curry(mul)
  138. double = cmul(2)
  139. assert callable(double)
  140. assert double(10) == 20
  141. assert repr(cmul) == repr(mul)
  142. cmap = curry(map)
  143. assert list(cmap(inc)([1, 2, 3])) == [2, 3, 4]
  144. assert raises(TypeError, lambda: curry())
  145. assert raises(TypeError, lambda: curry({1: 2}))
  146. def test_curry_kwargs():
  147. def f(a, b, c=10):
  148. return (a + b) * c
  149. f = curry(f)
  150. assert f(1, 2, 3) == 9
  151. assert f(1)(2, 3) == 9
  152. assert f(1, 2) == 30
  153. assert f(1, c=3)(2) == 9
  154. assert f(c=3)(1, 2) == 9
  155. def g(a=1, b=10, c=0):
  156. return a + b + c
  157. cg = curry(g, b=2)
  158. assert cg() == 3
  159. assert cg(b=3) == 4
  160. assert cg(a=0) == 2
  161. assert cg(a=0, b=1) == 1
  162. assert cg(0) == 2 # pass "a" as arg, not kwarg
  163. assert raises(TypeError, lambda: cg(1, 2)) # pass "b" as arg AND kwarg
  164. def h(x, func=int):
  165. return func(x)
  166. # __init__ must not pick func as positional arg
  167. assert curry(h)(0.0) == 0
  168. assert curry(h)(func=str)(0.0) == '0.0'
  169. assert curry(h, func=str)(0.0) == '0.0'
  170. def test_curry_passes_errors():
  171. @curry
  172. def f(a, b):
  173. if not isinstance(a, int):
  174. raise TypeError()
  175. return a + b
  176. assert f(1, 2) == 3
  177. assert raises(TypeError, lambda: f('1', 2))
  178. assert raises(TypeError, lambda: f('1')(2))
  179. assert raises(TypeError, lambda: f(1, 2, 3))
  180. def test_curry_docstring():
  181. def f(x, y):
  182. """ A docstring """
  183. return x
  184. g = curry(f)
  185. assert g.__doc__ == f.__doc__
  186. assert str(g) == str(f)
  187. assert f(1, 2) == g(1, 2)
  188. def test_curry_is_like_partial():
  189. def foo(a, b, c=1):
  190. return a + b + c
  191. p, c = partial(foo, 1, c=2), curry(foo)(1, c=2)
  192. assert p.keywords == c.keywords
  193. assert p.args == c.args
  194. assert p(3) == c(3)
  195. p, c = partial(foo, 1), curry(foo)(1)
  196. assert p.keywords == c.keywords
  197. assert p.args == c.args
  198. assert p(3) == c(3)
  199. assert p(3, c=2) == c(3, c=2)
  200. p, c = partial(foo, c=1), curry(foo)(c=1)
  201. assert p.keywords == c.keywords
  202. assert p.args == c.args
  203. assert p(1, 2) == c(1, 2)
  204. def test_curry_is_idempotent():
  205. def foo(a, b, c=1):
  206. return a + b + c
  207. f = curry(foo, 1, c=2)
  208. g = curry(f)
  209. assert isinstance(f, curry)
  210. assert isinstance(g, curry)
  211. assert not isinstance(g.func, curry)
  212. assert not hasattr(g.func, 'func')
  213. assert f.func == g.func
  214. assert f.args == g.args
  215. assert f.keywords == g.keywords
  216. def test_curry_attributes_readonly():
  217. def foo(a, b, c=1):
  218. return a + b + c
  219. f = curry(foo, 1, c=2)
  220. assert raises(AttributeError, lambda: setattr(f, 'args', (2,)))
  221. assert raises(AttributeError, lambda: setattr(f, 'keywords', {'c': 3}))
  222. assert raises(AttributeError, lambda: setattr(f, 'func', f))
  223. assert raises(AttributeError, lambda: delattr(f, 'args'))
  224. assert raises(AttributeError, lambda: delattr(f, 'keywords'))
  225. assert raises(AttributeError, lambda: delattr(f, 'func'))
  226. def test_curry_attributes_writable():
  227. def foo(a, b, c=1):
  228. return a + b + c
  229. foo.__qualname__ = 'this.is.foo'
  230. f = curry(foo, 1, c=2)
  231. assert f.__qualname__ == 'this.is.foo'
  232. f.__name__ = 'newname'
  233. f.__doc__ = 'newdoc'
  234. f.__module__ = 'newmodule'
  235. f.__qualname__ = 'newqualname'
  236. assert f.__name__ == 'newname'
  237. assert f.__doc__ == 'newdoc'
  238. assert f.__module__ == 'newmodule'
  239. assert f.__qualname__ == 'newqualname'
  240. if hasattr(f, 'func_name'):
  241. assert f.__name__ == f.func_name
  242. def test_curry_module():
  243. from cytoolz.curried.exceptions import merge
  244. assert merge.__module__ == 'cytoolz.curried.exceptions'
  245. def test_curry_comparable():
  246. def foo(a, b, c=1):
  247. return a + b + c
  248. f1 = curry(foo, 1, c=2)
  249. f2 = curry(foo, 1, c=2)
  250. g1 = curry(foo, 1, c=3)
  251. h1 = curry(foo, c=2)
  252. h2 = h1(c=2)
  253. h3 = h1()
  254. assert f1 == f2
  255. assert not (f1 != f2)
  256. assert f1 != g1
  257. assert not (f1 == g1)
  258. assert f1 != h1
  259. assert h1 == h2
  260. assert h1 == h3
  261. # test function comparison works
  262. def bar(a, b, c=1):
  263. return a + b + c
  264. b1 = curry(bar, 1, c=2)
  265. assert b1 != f1
  266. assert {f1, f2, g1, h1, h2, h3, b1, b1()} == {f1, g1, h1, b1}
  267. # test unhashable input
  268. unhash1 = curry(foo, [])
  269. assert raises(TypeError, lambda: hash(unhash1))
  270. unhash2 = curry(foo, c=[])
  271. assert raises(TypeError, lambda: hash(unhash2))
  272. def test_curry_doesnot_transmogrify():
  273. # Early versions of `curry` transmogrified to `partial` objects if
  274. # only one positional argument remained even if keyword arguments
  275. # were present. Now, `curry` should always remain `curry`.
  276. def f(x, y=0):
  277. return x + y
  278. cf = curry(f)
  279. assert cf(y=1)(y=2)(y=3)(1) == f(1, 3)
  280. def test_curry_on_classmethods():
  281. class A(object):
  282. BASE = 10
  283. def __init__(self, base):
  284. self.BASE = base
  285. @curry
  286. def addmethod(self, x, y):
  287. return self.BASE + x + y
  288. @classmethod
  289. @curry
  290. def addclass(cls, x, y):
  291. return cls.BASE + x + y
  292. @staticmethod
  293. @curry
  294. def addstatic(x, y):
  295. return x + y
  296. a = A(100)
  297. assert a.addmethod(3, 4) == 107
  298. assert a.addmethod(3)(4) == 107
  299. assert A.addmethod(a, 3, 4) == 107
  300. assert A.addmethod(a)(3)(4) == 107
  301. assert a.addclass(3, 4) == 17
  302. assert a.addclass(3)(4) == 17
  303. assert A.addclass(3, 4) == 17
  304. assert A.addclass(3)(4) == 17
  305. assert a.addstatic(3, 4) == 7
  306. assert a.addstatic(3)(4) == 7
  307. assert A.addstatic(3, 4) == 7
  308. assert A.addstatic(3)(4) == 7
  309. # we want this to be of type curry
  310. assert isinstance(a.addmethod, curry)
  311. assert isinstance(A.addmethod, curry)
  312. def test_memoize_on_classmethods():
  313. class A(object):
  314. BASE = 10
  315. HASH = 10
  316. def __init__(self, base):
  317. self.BASE = base
  318. @memoize
  319. def addmethod(self, x, y):
  320. return self.BASE + x + y
  321. @classmethod
  322. @memoize
  323. def addclass(cls, x, y):
  324. return cls.BASE + x + y
  325. @staticmethod
  326. @memoize
  327. def addstatic(x, y):
  328. return x + y
  329. def __hash__(self):
  330. return self.HASH
  331. a = A(100)
  332. assert a.addmethod(3, 4) == 107
  333. assert A.addmethod(a, 3, 4) == 107
  334. a.BASE = 200
  335. assert a.addmethod(3, 4) == 107
  336. a.HASH = 200
  337. assert a.addmethod(3, 4) == 207
  338. assert a.addclass(3, 4) == 17
  339. assert A.addclass(3, 4) == 17
  340. A.BASE = 20
  341. assert A.addclass(3, 4) == 17
  342. A.HASH = 20 # hashing of class is handled by metaclass
  343. assert A.addclass(3, 4) == 17 # hence, != 27
  344. assert a.addstatic(3, 4) == 7
  345. assert A.addstatic(3, 4) == 7
  346. def test_curry_call():
  347. @curry
  348. def add(x, y):
  349. return x + y
  350. assert raises(TypeError, lambda: add.call(1))
  351. assert add(1)(2) == add.call(1, 2)
  352. assert add(1)(2) == add(1).call(2)
  353. def test_curry_bind():
  354. @curry
  355. def add(x=1, y=2):
  356. return x + y
  357. assert add() == add(1, 2)
  358. assert add.bind(10)(20) == add(10, 20)
  359. assert add.bind(10).bind(20)() == add(10, 20)
  360. assert add.bind(x=10)(y=20) == add(10, 20)
  361. assert add.bind(x=10).bind(y=20)() == add(10, 20)
  362. def test_curry_unknown_args():
  363. def add3(x, y, z):
  364. return x + y + z
  365. @curry
  366. def f(*args):
  367. return add3(*args)
  368. assert f()(1)(2)(3) == 6
  369. assert f(1)(2)(3) == 6
  370. assert f(1, 2)(3) == 6
  371. assert f(1, 2, 3) == 6
  372. assert f(1, 2)(3, 4) == f(1, 2, 3, 4)
  373. def test_curry_bad_types():
  374. assert raises(TypeError, lambda: curry(1))
  375. def test_curry_subclassable():
  376. class mycurry(curry):
  377. pass
  378. add = mycurry(lambda x, y: x+y)
  379. assert isinstance(add, curry)
  380. assert isinstance(add, mycurry)
  381. assert isinstance(add(1), mycurry)
  382. assert isinstance(add()(1), mycurry)
  383. assert add(1)(2) == 3
  384. # Should we make `_should_curry` public?
  385. """
  386. class curry2(curry):
  387. def _should_curry(self, args, kwargs, exc=None):
  388. return len(self.args) + len(args) < 2
  389. add = curry2(lambda x, y: x+y)
  390. assert isinstance(add(1), curry2)
  391. assert add(1)(2) == 3
  392. assert isinstance(add(1)(x=2), curry2)
  393. assert raises(TypeError, lambda: add(1)(x=2)(3))
  394. """
  395. def generate_compose_test_cases():
  396. """
  397. Generate test cases for parametrized tests of the compose function.
  398. """
  399. def add_then_multiply(a, b, c=10):
  400. return (a + b) * c
  401. return (
  402. (
  403. (), # arguments to compose()
  404. (0,), {}, # positional and keyword args to the Composed object
  405. 0 # expected result
  406. ),
  407. (
  408. (inc,),
  409. (0,), {},
  410. 1
  411. ),
  412. (
  413. (double, inc),
  414. (0,), {},
  415. 2
  416. ),
  417. (
  418. (str, iseven, inc, double),
  419. (3,), {},
  420. "False"
  421. ),
  422. (
  423. (str, add),
  424. (1, 2), {},
  425. '3'
  426. ),
  427. (
  428. (str, inc, add_then_multiply),
  429. (1, 2), {"c": 3},
  430. '10'
  431. ),
  432. )
  433. def test_compose():
  434. for (compose_args, args, kw, expected) in generate_compose_test_cases():
  435. assert compose(*compose_args)(*args, **kw) == expected
  436. def test_compose_metadata():
  437. # Define two functions with different names
  438. def f(a):
  439. return a
  440. def g(a):
  441. return a
  442. composed = compose(f, g)
  443. assert composed.__name__ == 'f_of_g'
  444. assert composed.__doc__ == 'lambda *args, **kwargs: f(g(*args, **kwargs))'
  445. # Create an object with no __name__.
  446. h = object()
  447. composed = compose(f, h)
  448. assert composed.__name__ == 'Compose'
  449. assert composed.__doc__ == 'A composition of functions'
  450. assert repr(composed) == 'Compose({!r}, {!r})'.format(f, h)
  451. assert composed == compose(f, h)
  452. assert composed == AlwaysEquals()
  453. assert not composed == compose(h, f)
  454. assert not composed == object()
  455. assert not composed == NeverEquals()
  456. assert composed != compose(h, f)
  457. assert composed != NeverEquals()
  458. assert composed != object()
  459. assert not composed != compose(f, h)
  460. assert not composed != AlwaysEquals()
  461. assert hash(composed) == hash(compose(f, h))
  462. assert hash(composed) != hash(compose(h, f))
  463. bindable = compose(str, lambda x: x*2, lambda x, y=0: int(x) + y)
  464. class MyClass:
  465. def __int__(self):
  466. return 8
  467. my_method = bindable
  468. my_static_method = staticmethod(bindable)
  469. assert MyClass.my_method(3) == '6'
  470. assert MyClass.my_method(3, y=2) == '10'
  471. assert MyClass.my_static_method(2) == '4'
  472. assert MyClass().my_method() == '16'
  473. assert MyClass().my_method(y=3) == '22'
  474. assert MyClass().my_static_method(0) == '0'
  475. assert MyClass().my_static_method(0, 1) == '2'
  476. assert compose(f, h).__wrapped__ is h
  477. if hasattr(cytoolz, 'sandbox'): # only test this with Python version (i.e., not Cython)
  478. assert compose(f, h).__class__.__wrapped__ is None
  479. # __signature__ is python3 only
  480. if PY3:
  481. def myfunc(a, b, c, *d, **e):
  482. return 4
  483. def otherfunc(f):
  484. return 'result: {}'.format(f)
  485. # set annotations compatibly with python2 syntax
  486. myfunc.__annotations__ = {
  487. 'a': int,
  488. 'b': str,
  489. 'c': float,
  490. 'd': int,
  491. 'e': bool,
  492. 'return': int,
  493. }
  494. otherfunc.__annotations__ = {'f': int, 'return': str}
  495. composed = compose(otherfunc, myfunc)
  496. sig = inspect.signature(composed)
  497. assert sig.parameters == inspect.signature(myfunc).parameters
  498. assert sig.return_annotation == str
  499. class MyClass:
  500. method = composed
  501. assert len(inspect.signature(MyClass().method).parameters) == 4
  502. def generate_compose_left_test_cases():
  503. """
  504. Generate test cases for parametrized tests of the compose function.
  505. These are based on, and equivalent to, those produced by
  506. enerate_compose_test_cases().
  507. """
  508. return tuple(
  509. (tuple(reversed(compose_args)), args, kwargs, expected)
  510. for (compose_args, args, kwargs, expected)
  511. in generate_compose_test_cases()
  512. )
  513. def test_compose_left():
  514. for (compose_left_args, args, kw, expected) in generate_compose_left_test_cases():
  515. assert compose_left(*compose_left_args)(*args, **kw) == expected
  516. def test_pipe():
  517. assert pipe(1, inc) == 2
  518. assert pipe(1, inc, inc) == 3
  519. assert pipe(1, double, inc, iseven) is False
  520. def test_complement():
  521. # No args:
  522. assert complement(lambda: False)()
  523. assert not complement(lambda: True)()
  524. # Single arity:
  525. assert complement(iseven)(1)
  526. assert not complement(iseven)(2)
  527. assert complement(complement(iseven))(2)
  528. assert not complement(complement(isodd))(2)
  529. # Multiple arities:
  530. both_even = lambda a, b: iseven(a) and iseven(b)
  531. assert complement(both_even)(1, 2)
  532. assert not complement(both_even)(2, 2)
  533. # Generic truthiness:
  534. assert complement(lambda: "")()
  535. assert complement(lambda: 0)()
  536. assert complement(lambda: None)()
  537. assert complement(lambda: [])()
  538. assert not complement(lambda: "x")()
  539. assert not complement(lambda: 1)()
  540. assert not complement(lambda: [1])()
  541. def test_do():
  542. inc = lambda x: x + 1
  543. assert do(inc, 1) == 1
  544. log = []
  545. assert do(log.append, 1) == 1
  546. assert log == [1]
  547. def test_juxt_generator_input():
  548. data = list(range(10))
  549. juxtfunc = juxt(itemgetter(2*i) for i in range(5))
  550. assert juxtfunc(data) == (0, 2, 4, 6, 8)
  551. assert juxtfunc(data) == (0, 2, 4, 6, 8)
  552. def test_flip():
  553. def f(a, b):
  554. return a, b
  555. assert flip(f, 'a', 'b') == ('b', 'a')
  556. def test_excepts():
  557. # These are descriptors, make sure this works correctly.
  558. assert excepts.__name__ == 'excepts'
  559. assert (
  560. 'A wrapper around a function to catch exceptions and\n'
  561. ' dispatch to a handler.\n'
  562. ) in excepts.__doc__
  563. def idx(a):
  564. """idx docstring
  565. """
  566. return [1, 2].index(a)
  567. def handler(e):
  568. """handler docstring
  569. """
  570. assert isinstance(e, ValueError)
  571. return -1
  572. excepting = excepts(ValueError, idx, handler)
  573. assert excepting(1) == 0
  574. assert excepting(2) == 1
  575. assert excepting(3) == -1
  576. assert excepting.__name__ == 'idx_excepting_ValueError'
  577. assert 'idx docstring' in excepting.__doc__
  578. assert 'ValueError' in excepting.__doc__
  579. assert 'handler docstring' in excepting.__doc__
  580. def getzero(a):
  581. """getzero docstring
  582. """
  583. return a[0]
  584. excepting = excepts((IndexError, KeyError), getzero)
  585. assert excepting([]) is None
  586. assert excepting([1]) == 1
  587. assert excepting({}) is None
  588. assert excepting({0: 1}) == 1
  589. assert excepting.__name__ == 'getzero_excepting_IndexError_or_KeyError'
  590. assert 'getzero docstring' in excepting.__doc__
  591. assert 'return_none' in excepting.__doc__
  592. assert 'Returns None' in excepting.__doc__
  593. def raise_(a):
  594. """A function that raises an instance of the exception type given.
  595. """
  596. raise a()
  597. excepting = excepts((ValueError, KeyError), raise_)
  598. assert excepting(ValueError) is None
  599. assert excepting(KeyError) is None
  600. assert raises(TypeError, lambda: excepting(TypeError))
  601. assert raises(NotImplementedError, lambda: excepting(NotImplementedError))
  602. excepting = excepts(object(), object(), object())
  603. assert excepting.__name__ == 'excepting'
  604. assert excepting.__doc__ == excepts.__doc__