Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Table Maker Class
#3
(Apr-09-2019, 09:03 AM)Gribouillis Wrote: The __all_strings() feature doesn't depend on the instance. You could provide it separately using functools.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
Reply


Messages In This Thread
Table Maker Class - by iMuny - Apr-09-2019, 08:00 AM
RE: Table Maker Class - by Gribouillis - Apr-09-2019, 09:03 AM
RE: Table Maker Class - by iMuny - Apr-09-2019, 09:23 AM
RE: Table Maker Class - by Ceegen - Apr-09-2019, 08:39 PM
RE: Table Maker Class - by iMuny - Apr-10-2019, 02:34 PM
RE: Table Maker Class - by Ceegen - Apr-12-2019, 11:02 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extremely Simple RPG Character File Maker ashtons 0 2,379 Jan-09-2018, 10:46 PM
Last Post: ashtons

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020