I am trying to write python2 and python3 compatible code which uses type function. Both return different strings in 2 v/s 3, which I have to assert in my unit tests.
Python 3.7.4 (default, Oct 18 2019, 15:58:40)
>>> type(2)
<class 'int'>
Python 2.7.16 (default, Jul 24 2019, 16:45:12)
>>> type(2)
<type 'int'>
The intention here is to validate the exception messages raised from my function. For example,
def func(arg1):
if not isinstance(arg1, int):
raise TypeError('Expected type %s but got %s' % (type(int), type(arg1)))
print("Function executed")
try:
func('str')
except TypeError as e:
assert e.args[0]== "Expected type <type 'type'> but got <type 'str'>"
print("Correct exception was raised")
Assertion here passes in python2 but fails in python3.
AttributeError: 'TypeError' object has no attribute 'message'in python 3. This is because the attributemessagefrom errors has been deprecated since python 2.6 according to: github.com/google/yapf/issues/564 It has been deprecated since python 2.6 and to look to: python.org/dev/peps/pep-0352 for further information. It seems like usinge.messagewill not allow for the code to work in both versions.