How to migrate the code using Six Module that will be compatible in python2 and python3 version

How to migrate the code using Six Module that will be compatible in python2 and python3 version

I want to provide six for compatible my code in python2 and python3 version. I have got the example from online but did not get more sources to get the six example in online. In the below code, i could not understand why they have created class for test cases and have written this line

class SampleTests(unittest.TestCase):

and inside main, how did they call the class SampleTests? and how unittest.main() inside main call the class?

Kindly help me. if possible kindly give some sample example of six module migration.

import six
from six.moves import reduce
import unittest


def multiply_values(val1, val2):
    return val1*val2

def add_values(val1, val2):
    return val1+val2

class SampleTests(unittest.TestCase):    
    def test_sets_equal(self):
        setValue1 = reduce(multiply_values, [1,2])
        setValue2 = reduce(add_values, [1,2])
        six.assertCountEqual(self, [2,3], [setValue1,setValue2])
    
if __name__ == '__main__':
    unittest.main()

答案1

In your example six is used for two things:

  • reduce was removed in Python 3 and replace by functools.reduce so six offers a handy "alias" for it so you can call reduce in both 2 and 3.
  • assertCountEqual is part of unittest in Python 3 so six here provides its own implementation for Python 2.

The best documentation for the six module is available here: https://six.readthedocs.io/

Note: Python 2 is deprecated now and you shouldn't be using it for new projects. six will help you write code that works on both versions of Python but if you don't have a good reason for supporting Python 2, it would be better to write a Python 3 only code. 2to3 tool can you help with converting Python 2 code to Python 3.

why they have created class for test cases and have written this line class SampleTests(unittest.TestCase): and Inside main, how did they call the class SampleTests

This isn't really six specific question, this is how the unittest module works on both Python 2 and 3, see https://docs.python.org/3/library/unittest.html for details.

TL;DR version: unittest.main() will automatically run all the test cases in the file and test case is defined as a function which name starts with test_ in a unittest.TestCase class.

相关内容