Detecting __future__ features

Antti Rasinen ars at iki.fi
Mon Jul 30 08:55:30 EDT 2007


On 2007-07-30, at 15:29, Steven D'Aprano wrote:

> How would one tell at runtime if a particular feature has been  
> enabled by
> the "from __future__ import thing" statement?
>
> (I don't especially care whether the feature in question has been  
> enabled
> via an explicit call to import, or because it has become the default.)
>
> Is there any general mechanism?

You probably have to care about imports vs. language defaults. But  
it's not very difficult.

For imports you can use __future__ to help you. If your namespace  
contains a feature you want to check for and it is identical to the  
same feature in __future__, then the code has used from __future__  
import feature. You could probably try something like this:

import __feature__
feature = "division"
if globals().get(feature, None) == __future__.__dict__[feature]:
     print "Bingo!"

You can probably figure out how to use sys.version_info to check  
whether the current Python version is higher than the one specified  
in a feature line:

import __future__
import sys
if sys.version_info >= __future__.division.mandatory:
     print "Bingo! Two in a row!"

Check the __future__ docstrings for more information.

-- 
[ ars at iki.fi <*> Antti Rasinen ]

This drone-vessel speaks with the voice and authority of the Ur-Quan.




More information about the Python-list mailing list