inheriting from long on Python2 or int on Python3

Terry Reedy tjreedy at udel.edu
Sat Mar 21 14:00:29 EDT 2020


On 3/21/2020 1:19 PM, duncan smith wrote:
> Hello,
>        I have a class I wrote for Python2 that needs to be made to work
> on Python3. On Python2 it inherited from long, so it needs to inherit
> from int on Python3.

In general, if you want code to work on both 2 and 3, look into the 
bi-version packages such as 'six' and 'future' and documents such as
https://python-future.org/compatible_idioms.html.

If 'long' appears more than once in your code, you might prefer using 
this at the top.

if sys.version_info.major >= 3:
     long = int

This has the plus of indicating that this is a 2 and 3 file, if anyone 
else reads it.

> The following works, but I'm not sure it's the cleanest solution.

It does not bother me.

> It's the first time I've wanted / needed to make a
> parent class conditional on the Python version, and I'm not sure it's
> even a good idea. I used inheritance because I wanted to perform bitwise
> operations on instances, but I could probably switch to composition.
> Just wondering how bad the following really is (in a code smell kind of
> a away). TIA.

> import sys
> 
> class C_hash(int if sys.version_info.major >= 3 else long):
>      def __new__(cls, bits, m, N=1):
>          obj = super(C_hash, cls).__new__(cls, bits)
>          obj._m = m
>          obj._N = N
>          return obj

-- 
Terry Jan Reedy



More information about the Python-list mailing list