Apr-09-2019, 09:23 AM
(Apr-09-2019, 09:03 AM)Gribouillis Wrote: The__all_strings()
feature doesn't depend on the instance. You could provide it separately usingfunctools.singledispatch()
from functools import singledispatch @singledispatch def all_string(ob): return str(ob).strip() @all_string.register(tuple) @all_string.register(list) @all_string.register(set) def _(ob): return type(ob)(all_string(x) for x in ob) @all_string.register(dict) def _(ob): return type(ob)(all_string(x) for x in ob.items()) #-------- TEST CODE -------- if __name__ == '__main__': import unittest as ut class TestAllString(ut.TestCase): def test_all_string_for_string_argument(self): sample = "Hello world " result = all_string(sample) self.assertEqual(result, sample.strip()) def test_all_string_for_list_argument(self): sample = ['a', 32, b'c', (1,2,3)] result = all_string(sample) self.assertEqual(result, ['a', '32', "b'c'", ('1', '2', '3')]) def test_all_string_for_tuple_argument(self): sample = ('a', 32, b'c', [1,2,3]) result = all_string(sample) self.assertEqual(result, ('a', '32', "b'c'", ['1', '2', '3'])) def test_all_string_for_set_argument(self): sample = set(('a', 32, b'c', (1,2,3))) result = all_string(sample) self.assertEqual(result, set(('a', '32', "b'c'", ('1', '2', '3')))) def test_all_string_for_dict_argument(self): sample = {'a':32, b'c': (1,2,3)} result = all_string(sample) self.assertEqual(result, {'a': '32', "b'c'": ('1', '2', '3')}) ut.main()
Thanks and wow that functools library is some really awesome mojo. I'm gonna read up more on it.
I don't understand the testing part very well, i see you seem to be checking if all_string is working as expected, I think.
I'll check out some tutorials on how the unittest class works and ask you if i don't understand something.
Thanks again