What is future in Python used for and how/when to use it, and how it works
The __future__
module in Python allows you to import features from future Python versions. This future-looking feature maintains the compatibility and longer life of your code.
To put it in action, use __future__
to import Python 3's print function while working in Python 2:
By doing this, your print statements are dressed for a future date, keeping your code in style with minimal alterations.
Deciding when to use future
Wondering when to use __future__
? Here's how to decide:
- If you want to future-proof your code against changes in upcoming Python versions.
- If you're preparing to upgrade to a newer version of Python and need your code to remain compatible.
- If you want a sneak peek at, or to start using, newer Python features before the full Python upgrade.
Changing division and print operations with future
Here's an illustrative use of __future__
:
And here's another:
Forward thinking: Compatibility with future versions
As you step towards the future, keep in mind:
- Testing: Does your code behave as expected after importing with
__future__
? - Code reviews: Are your
__future__
imports necessary and correct? Discuss and review with your team. - Documentation: Keep track of your
__future__
imports to explain why you have chosen to use them.
Digging deeper: How future actually works
__future__
imports behave like compiler directives. They change the Python interpreter’s rules. What you should know:
- Up-to-date: You can find out when a
__future__
feature was added and when it will become a default feature. - Rules change: Normal imports just import code or functions.
__future__
imports change the language rules itself. Yes, it's most certainly a rebel. - Working with old code: Need to update that decades-old codebase? Use
__future__
to get with the times without rewriting everything.
Notable future transitions
Some of the notable shifts experienced through __future__
:
nested_scopes
: This was the time when inner functions got access to outer functions.generators
: Introduced theyield
keyword, lazy evaluation became a thing then.unicode_literals
: Owing to__future__
, Python 2.x started interpreting string literals as unicode, just as Python 3.x did.
Pushing the limits: Maximizing current interpreter value
By using __future__
imports, you essentially increase the value of your current Python interpreter by using newer features while remaining within the stable and tested ecosystem of your current Python version or software.
The future is now: Watch out for backward compatibility issues!
One thing to caution when going __future__
way: backward compatibility might take a hit. Bringing features from the future might make your code incompatible with older versions. Tread carefully, and preemptively manage deployment issues.
Was this article helpful?