|
1 | 1 | from collections import OrderedDict |
2 | 2 | from collections.abc import Iterable |
3 | | -from functools import reduce |
| 3 | +from functools import reduce, wraps |
4 | 4 | from itertools import chain, combinations, groupby, product, zip_longest |
5 | 5 | from operator import attrgetter, mul |
6 | 6 | import types |
|
12 | 12 | 'roundm', 'powerset', 'invert', 'flatten', 'single_or', 'filter_ordered', |
13 | 13 | 'as_mapper', 'filter_sorted', 'pprint', 'sweep', 'all_equal', 'as_list', |
14 | 14 | 'indices_to_slices', 'indices_to_sections', 'transitive_closure', |
15 | | - 'humanbytes', 'contains_val', 'sorted_priority', 'as_set', 'is_number'] |
| 15 | + 'humanbytes', 'contains_val', 'sorted_priority', 'as_set', 'is_number', |
| 16 | + 'smart_lt', 'smart_gt'] |
16 | 17 |
|
17 | 18 |
|
18 | 19 | def prod(iterable, initial=1): |
@@ -346,3 +347,35 @@ def key(i): |
346 | 347 | return (v, str(type(i))) |
347 | 348 |
|
348 | 349 | return sorted(items, key=key, reverse=True) |
| 350 | + |
| 351 | + |
| 352 | +def avoid_symbolic(default=None): |
| 353 | + """ |
| 354 | + Decorator to avoid calling a function where doing so will result in symbolic |
| 355 | + computation being performed. For use if symbolic computation may be slow. In |
| 356 | + the case that an arg is symbolic, just give up and return a default value. |
| 357 | + """ |
| 358 | + def _avoid_symbolic(func): |
| 359 | + @wraps(func) |
| 360 | + def wrapper(*args): |
| 361 | + if any(isinstance(expr, sympy.Basic) for expr in args): |
| 362 | + # An argument is symbolic, so give up and assume default |
| 363 | + return default |
| 364 | + |
| 365 | + return func(*args) |
| 366 | + |
| 367 | + return wrapper |
| 368 | + |
| 369 | + return _avoid_symbolic |
| 370 | + |
| 371 | + |
| 372 | +@avoid_symbolic(default=False) |
| 373 | +def smart_lt(a, b): |
| 374 | + """An Lt that gives up and returns False if supplied a symbolic argument""" |
| 375 | + return a < b |
| 376 | + |
| 377 | + |
| 378 | +@avoid_symbolic(default=False) |
| 379 | +def smart_gt(a, b): |
| 380 | + """A Gt that gives up and returns False if supplied a symbolic argument""" |
| 381 | + return a > b |
0 commit comments