inheriting from long on Python2 or int on Python3

Chris Angelico rosuav at gmail.com
Sat Mar 21 15:52:05 EDT 2020


On Sun, Mar 22, 2020 at 4:21 AM duncan smith <duncan at invalid.invalid> 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. The following works, but I'm not sure it's the
> cleanest solution. 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.

try: int = long
except NameError: pass

Then just inherit from int. On Py3 it'll just work fine, and you can
drop those two lines of code once you drop Py2 support. On Py2 (which
is becoming less and less important now), it'll do that assignment.

Alternatively, don't worry about Py2 any more, and just change it to
inherit from it.

ChrisA


More information about the Python-list mailing list