import all future features
Asked Answered
E

3

5

Just curious, I tried from __future__ import *, but I received this error:

  File "<stdin>", line 1
SyntaxError: future feature * is not defined

Well, that makes sense. A __future__ import is a little special and doesn't follow the normal rules, but it got me to thinking: how can I import all the future features?

Eutrophic answered 29/7, 2016 at 1:20 Comment(0)
M
11

You can't, and that's by design. This is because more __future__ features might be added in the future, and those can break your code.

Imagine that in 2.x, the only __future__ feature was division. Then in 2.y, a new __future__ feature, print_function, is introduced. All of a sudden my code has broken:

from __future__ import *
print "Hello, World!"

You can, however, import __future__, and inspect its contents:

>>> import __future__
>>> [x for x in dir(__future__) if x.islower() and x[0] != '_']
['absolute_import', 'all_feature_names', 'division', 'generator_stop', 'generators', 'nested_scopes', 'print_function', 'unicode_literals', 'with_statement']

Note that these are not features and you should not try to import them. They instead describe which features are available, and from which versions they are.

Marcelenemarcelia answered 29/7, 2016 at 1:22 Comment(0)
P
1

The current maximal import would be:

from __future__ import absolute_import, division, print_function, unicode_literals

If I had to guess, that will be good until the end of the Python 2.7 series in 2020. There's no harm in including the old ones, like generators, but it's a no-op once the feature is standard.

Plainsman answered 6/3, 2019 at 23:26 Comment(1)
This is outdated, annotations is missing.Raid
C
0

You actually can import every feature from __future__ (with a small workaround). The following code lines are all one-liners and highly compressed.

Python >= 3.6:

[exec(f"from __future__ import {x}") for x in dir(__import__("__future__")) if x.islower() and not x.startswith("all_") and x[0] != '_']

Python < 3.6:

[exec(f"from __future__ import "+x) for x in dir(__import__("__future__")) if x.islower() and not x.startswith("all_") and x[0] != '_']

Note:
You don't have to assign the resulting list to a variable because it contains only Nones.

A simple text version of these snippets:
Import everything of a list of everything in __future__ that contains only lower case letters, does not start with all_ and whose first letter is not _.

Concurrence answered 26/7, 2023 at 17:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.