3

I am using Python doctests for a code which is supposed to work with Python 2 and Python 3. All works fine except for when I work with numpy array containing strings. With Python 3, the following is correct:

>>> np.array(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"])   # doctest: +NORMALIZE_WHITESPACE
array(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
       'oct', 'nov', 'dec'],
      dtype='<U3')

With Python 2, this result is expected:

array(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
       'oct', 'nov', 'dec'],
      dtype='|S3')

Note the <U3 vs. |S3 difference.

Is there any easy way to tweak my code to be able to pass the tests in both Python versions? I want to do the lease intrusive changes possible. As doctests are also targeting users (so they can see how to use the code) I do not want too complicated or misleading code to give them wrong impression of the correct usage.

1 Answers1

1

I don't know if this will be acceptable for you or not, but the difference is only visible in the __repr__:

>>> A = np.array(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"])
>>> A
array(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
       'oct', 'nov', 'dec'], 
      dtype='|S3')

So if you change your doctests to check the printed output of the array, it should be compatible.

>>> print(A)
['jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec']

It's a hacky workaround at best, but doctests are very limiting and not flexible for python 2 / python 3 compatibility.

wim
  • 338,267
  • 99
  • 616
  • 750