0

I have a code in Python 2 which I would like to convert to Python 3, however the behaviour of the code MUST remain exactly the same as on Python 2 interpreter.

Especially division must behave like on Python 2 interpreter.

I tried with futurize stage 1 and 2 but division remains just / on the code, which generates errors on execution because returned number is of type float instead of type int (which was a default behaviour for code executed on Python 2 interpreter).

EDIT: 3 // 2 = 1.0 which is float in Python 3. Is there a way to return int?

0

2 Answers 2

1

Futurize/Modernize/2to3 can't statically analyze which divisions are integer division.

You will need to manually go through division operations in the converted code and figure out which should use // for integer division and which should use / for real division.

Naturally, your code base's test cases should find any regressions here. ;)

Sign up to request clarification or add additional context in comments.

6 Comments

But if all Python 2 divisions with / are type int - there should be a futurize flag to change all those / into //. At least on your own risk.
Then you should be able to just search-and-replace for ` / ` -> ` // ` (taking care not to change anything that might be in string literals or similar of course).
that's why I'm asking - to not convert strings with simple replace. I have 100+/ matches in 11 files and I'm sure I want to change all / div to //.
Well, if it helps, PyCharm's search-and-replace feature has a filter for "Except Comments and String Literals" :)
well, that's may be helpful, but I can't believe there is no way to do this (on your own risk) by Futurize/Modernize/2to3.
|
0

The integer division operator is // in python 3.

>>> 3 / 2
1.5
>>> 3 // 2
1

edit: The only way I know of to get compatible behavior from both versions of python is to futurize the python 2 / operation and to convert any instances that expect integer division in the python 2 program to instead use // which works for integer divisions in both python 2 and 3.

4 Comments

thanks ;) But how can I forced futurize to change all those divisions? Because if I simply replace / with // it can generate other errors
if you want code compatible with both python 2 and 3 i'd use the python 3 operation for / instead. You can futurize the division in the python 2 program and update the instances where you need integer division to use // which also does integer division in python 2
3 // 2 = 1.0 which is float. Is there a way to return int?
@Ziemo: 3 // 2 => 1 in Python 3 (result type int)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.