__future__
frequently appears in Python modules. I do not understand what __future__
is for and how/when to use it even after reading the Python's __future__
doc.
Can anyone explain with examples?
A few answers regarding the basic usage of __future__
I've received seemed correct.
However, I need to understand one more thing regarding how __future__
works:
The most confusing concept for me is how a current python release includes features for future releases, and how a program using a feature from a future release can be be compiled successfully in the current version of Python.
I am guessing that the current release is packaged with potential features for the future. However, the features are available only by using __future__
because they are not the current standard. Let me know if I am right.
__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module.
The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.
A Future represents an eventual result of an asynchronous operation. Not thread-safe. Future is an awaitable object. Coroutines can await on Future objects until they either have a result or an exception set, or until they are cancelled.
That's the whole point of from __future__ import print_function ; to bring the print function from Python 3 into Python 2.6+. __future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning.
With __future__
module's inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.
E.g., for using context managers, you had to do from __future__ import with_statement
in 2.5, as the with
keyword was new and shouldn't be used as variable names any longer. In order to use with
as a Python keyword in Python 2.5 or older, you will need to use the import from above.
Another example is
from __future__ import division print 8/7 # prints 1.1428571428571428 print 8//7 # prints 1
Without the __future__
stuff, both print
statements would print 1
.
The internal difference is that without that import, /
is mapped to the __div__()
method, while with it, __truediv__()
is used. (In any case, //
calls __floordiv__()
.)
Apropos print
: print
becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.
>>> print >>> from __future__ import print_function >>> print <built-in function print> >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With