Bharadwaj Raju Bharadwaj Raju - 26 days ago 6
Python Question

How to detect whether Python variable is an import from future

How can we detect if a Python variable is an import from

__future__
?

I've noticed it's a class, specifically,
__future__._Feature()
. However, all attempts at importing that class seem to fail.

type()
returns
<class '__future__._Feature'>


My attempts at getting the
_Feature
class:



>>> from __future__ import absolute_import

>>> absolute_import
_Feature((2, 5, 0, 'alpha', 1), (3, 0, 0, 'alpha', 0), 16384)

>>> type(abolute_import)
<class '__future__._Feature'>

>>> from __future__ import _Feature
SyntaxError: future feature _Feature is not defined

>>> import __future__._Feature
ImportError: No module named '__future__._Feature'; '__future__' is not a package

>>>

Answer

The way to do it is to extract the type from a known "_Feature" and use that:

from __future__ import division
Feature = type(division)

from __future__ import unicode_literals
isinstance(unicode_literals, Feature)

(yields True)

That may look a "hack" - but it is actually the way to retrieve a couple of classes defined in native code that are not available for direct importing. The much more useful FunctionType can be imported with from types import FunctionType - but if you open the Python file for the types module, you will see it is declared as something like: FunctionType = type(lambda: None)

That said, I wonder what is the motivation for you to check the type of a _Feature of the __future__ imports - these are mostly placeholders so that it is possible to use the import syntax to enable the features. The changes __future__ imports cause goes directly into the each compiled code object, as a flag, and changes the behavior of byte code execution itself. You can certainly delete these _Feature objects from your module, and the feature itself will still be enabled for that module -

>>> from __future__ import division
>>> del division
>>> 5 / 2
2.5