__future__ import is not the first non-docstring statement¶
__future__ module enables a module to use functionality that is mandatory in future Python versions. If it was possible to place the
__future__ module in the middle of a module, then that would mean that one half of the module could use the old Python functionality for a given feature, and the other half (after the
__future__ import) could use the new Python functionality of the feature. This could create many strange and hard-to-find bugs, so Python does not allow it.
The code below attempts to place a
__future__ import statement in the middle of the module. When Python encounters the
from __future__ import division statement it raises a
SyntaxError and halts execution. However, if the code were to execute, the first
1 (which is how the division operator behaves in Python versions 2 and below), but the second
__future__ import statements in the middle of a module. The module can use either version of the division operator, but it can’t use both.
print(8 / 7) # 1 # SyntaxError from __future__ import division # 1.1428571428571428 print(8 / 7)
In the modified code below, the author decides that the module needs to use the old functionality of the division operator. The only solution in this case is to remove the
__future__ import statement from the module.
# removed __future__ import statement print(8 / 7) # 1
__future__ import before all other statements¶
In the modified code below, the author decides that the module needs the new functionality of the division operator. The only solution then is to place the
__future__ import statement at the beginning of the module
from __future__ import division # 1.1428571428571428 print(8 / 7)
- PyLint - W0410, misplaced-future
- Simeon Visser - How does ‘from __future__ import …’ work?
- Python Standard Library - __future__