Skip to content

Commit

Permalink
feat(value_2_list): add function to cast single value to a list
Browse files Browse the repository at this point in the history
  • Loading branch information
Axel Fahy committed Sep 26, 2019
1 parent bbf718a commit b5fe6b3
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 3 deletions.
1 change: 1 addition & 0 deletions .pylintrc
Expand Up @@ -139,6 +139,7 @@ disable=print-statement,
deprecated-sys-function,
exception-escape,
comprehension-escape,
logging-format-interpolation,
logging-fstring-interpolation

# Enable the message, report, category or checker with the given id(s). You can
Expand Down
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -50,6 +50,9 @@ As of *v0.2*, plots are not yet tested in the travis build.

## Release History

* 0.2.2
* FIX: Function ``value_2_list`` renamed to ``kwargs_2_list``.
* ADD: Function ``value_2_list`` to cast a single value.
* 0.2.1
* ADD: Function ``plot_counter`` to plot counter as bar plot.
* 0.2.0
Expand Down
2 changes: 2 additions & 0 deletions bff/__init__.py
Expand Up @@ -16,6 +16,7 @@
parse_date,
read_sql_by_chunks,
sliding_window,
value_2_list,
)

from .config import FancyConfig
Expand All @@ -33,6 +34,7 @@
'read_sql_by_chunks',
'sliding_window',
'FancyConfig',
'value_2_list',
]

# Logging configuration.
Expand Down
37 changes: 35 additions & 2 deletions bff/fancy.py
Expand Up @@ -11,6 +11,7 @@
from typing import Any, Callable, Dict, Hashable, List, Sequence, Set, Union
from dateutil import parser
from scipy import signal
import numpy as np
import pandas as pd

LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -284,8 +285,7 @@ def kwargs_2_list(**kwargs) -> Dict[str, Sequence]:
{'countries': ['Swiss', 'Spain']}
"""
for k, v in kwargs.items():
if not isinstance(v, collections.abc.Sequence) or isinstance(v, str):
kwargs[k] = [v]
kwargs[k] = value_2_list(v)
return kwargs


Expand Down Expand Up @@ -532,3 +532,36 @@ def sliding_window(sequence: Sequence, window_size: int, step: int):
if mod:
start = len(sequence) - (window_size - step) - mod
yield sequence[start:]


def value_2_list(value: Any) -> Sequence:
"""
Convert a single value into a list with a single value.
If the value is alredy a sequence, it is returned without modification.
Type `np.ndarray` is not put inside another sequence.
Strings are not considered as a sequence in this scenario.
Parameters
----------
value
Value to convert to a sequence.
Returns
-------
sequence
Value put into a sequence.
Examples
--------
>>> value_2_list(42)
[42]
>>> value_2_list('Swiss')
['Swiss']
>>> value_2_list('Swiss')
['Swiss']
"""
if (not isinstance(value, (collections.abc.Sequence, np.ndarray)) or isinstance(value, str)):
value = [value]
return value
1 change: 1 addition & 0 deletions doc/source/fancy.rst
Expand Up @@ -21,4 +21,5 @@ All of bff's functions.
bff.plot.plot_true_vs_pred
bff.read_sql_by_chunks
bff.sliding_window
bff.value_2_list

25 changes: 24 additions & 1 deletion tests/test_fancy.py
Expand Up @@ -6,14 +6,15 @@
import datetime
import unittest
import unittest.mock
import matplotlib.pyplot as plt
import numpy as np
from numpy.testing import assert_array_equal
import pandas as pd
from pandas.api.types import CategoricalDtype
import pandas.util.testing as tm

from bff.fancy import (cast_to_category_pd, concat_with_categories, get_peaks, idict,
mem_usage_pd, parse_date, kwargs_2_list, sliding_window)
kwargs_2_list, mem_usage_pd, parse_date, sliding_window, value_2_list)


class TestFancy(unittest.TestCase):
Expand Down Expand Up @@ -277,6 +278,28 @@ def test_sliding_window(self):
with self.assertRaises(ValueError):
list(sliding_window('abc', 4, 1))

def test_value_2_list(self):
"""
Test of the `value_2_list` function.
"""
# A list should remain a list.
self.assertEqual(value_2_list([1, 2, 3]), [1, 2, 3])
# A single integer should result in a list with one integer.
self.assertEqual(value_2_list(42), [42])
# A single string should result in a list with one string.
self.assertEqual(value_2_list('John Doe'), ['John Doe'])
# A tuple should remain a tuple.
self.assertEqual(value_2_list(('Jane Doe', 14)), ('Jane Doe', 14))
# A dictionary should result in a list with the dictionary.
self.assertEqual(value_2_list({'name': 'John Doe', 'age': 42}),
[{'name': 'John Doe', 'age': 42}])
# A single axis should be put in a list.
__, axes_a = plt.subplots(nrows=1, ncols=1)
self.assertEqual(len(value_2_list(axes_a)), 1)
# A list of axis (`np.ndarray`) should not change.
__, axes_b = plt.subplots(nrows=2, ncols=1)
self.assertEqual(len(value_2_list(axes_b)), 2)


if __name__ == '__main__':
unittest.main()

0 comments on commit b5fe6b3

Please sign in to comment.