Skip to content
Snippets Groups Projects
Commit 0d501267 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

add intify

parent 86ab5b39
No related branches found
No related tags found
No related merge requests found
# v2.11.36
* added `intify`
......@@ -12,6 +12,8 @@ Functions and decorators
.. autofunction:: satella.coding.queue_iterator
.. autofunction:: satella.coding.transforms.intify
.. autofunction:: satella.coding.transforms.jsonify
.. autofunction:: satella.coding.update_key_if_not_none
......
__version__ = '2.11.36_a1'
__version__ = '2.11.36_a2'
......@@ -8,7 +8,7 @@ from .merger import merge_series
from .jsonify import jsonify
__all__ = ['stringify', 'split_shuffle_and_join', 'one_tuple',
'merge_series', 'pad_to_multiple_of_length', 'clip',
'jsonify']
'jsonify', 'intify']
T = tp.TypeVar('T')
Number = tp.Union[int, float]
......@@ -86,6 +86,33 @@ def one_tuple(x: tp.Iterable[T]) -> tp.Iterator[tp.Tuple[T]]:
yield z,
def intify(v: tp.Any) -> int:
"""
Attempt to convert v to an int.
None will be converted to 0.
Any object will have int() called on it.
Failing that, it's length will be taken.
Failing that, ValueError will be raised
:param v: parameter
:return: int representation
"""
if v is None:
return 0
try:
return int(v)
except (TypeError, ValueError):
try:
return len(v)
except (AttributeError, TypeError, ValueError):
raise ValueError('Unable to convert %s to int' % (v, ))
def split_shuffle_and_join(entries: tp.List[T],
whether_to_shuffle: tp.Callable[[T], bool] = lambda x: True,
not_shuffled_to_front: bool = True) -> tp.List[T]:
......
......@@ -2,11 +2,17 @@ import unittest
from satella.coding import update_key_if_not_none, overload, class_or_instancemethod, \
update_key_if_true, get_arguments, call_with_arguments
from satella.coding.transforms import jsonify
from satella.coding.transforms import jsonify, intify
class TestCase(unittest.TestCase):
def test_intify(self):
self.assertEqual(intify(None), 0)
self.assertEqual(intify('2'), 2)
self.assertRaises(ValueError, lambda: intify(object()))
self.assertEqual(intify([1, 2, 3]), 3)
def test_execute_with_locals(self):
def fun(a, b, *args, c=None, **kwargs):
if len(kwargs):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment