Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I add __future__ statements to every file on my project?

I am contributing code to a currently only Python 2 project to allow it to run on Python 3. Should I put the following import:

from __future__ import (unicode_literals, print_function,
                        absolute_imports, division)

On every file on the project or just use the ones I need on each file?

like image 226
m45t3r Avatar asked Mar 29 '14 15:03

m45t3r


1 Answers

As far as I know there isn't any explicit convention about this, however I'd be inclined to add all of them in every file.

You may know what __future__ features you are using now, but what if in the future the file is modified and suddenly requires an other feature or doesn't require a certain feature any more?

  • If you put all of them on every file then you already know that you can write everything in "python3 style" and be sure that no strange bugs/errors occur. There is no problem if a certain feature isn't used.
  • If you don't then there's a chance that you:
    • Forget to add the import for the feature, even though you know it's required.
    • Don't realize you actually need a new feature because you are used to it and don't always keep in mind that it's a python3 feature
    • Forget to remove an unused feature import. Note that this usually requires a review of the whole file to be sure you don't need a feature.

Putting all the imports always let you write python3-like code, which means you don't have to keep in mind exactly what features are on/off in a specific file. You just write python3.

On the other hand, when selecting the features to import, you have to adjust how you code in a per-file basis depending on the features active in the file.

Yet an other reason to prefer the first solution is that IDEs usually provide a way to specify the template for new files, which means you don't even have to remember to add all the imports yourself, the IDE will do that for you.


There's only one catch in this reasoning: that adding the imports doesn't break the code. This obviously isn't guaranteed. However the changes you'd have to do you should already do them to port the software for python3, so it shouldn't increase the amount of time required to port the software.

like image 165
Bakuriu Avatar answered Oct 12 '22 20:10

Bakuriu