A pleasing Python regularity with __future__

April 7, 2006

The other night I was writing a Python program that wanted to divide two integers and get a floating point result. Normally integer division in Python produces integers, following a C style model of distinct numeric types; however, Python is slowly migrating towards a model where the types of numbers are more of an implementation detail.

The general way to get early access to an incompatible change like this is a magic statement at the start of your module: from __future__ import whatever. I knew that the change in number behavior could be gotten this way, but I couldn't remember what the magic whatever for it was.

After a moment's thought, I decided to try something:

>>> import __future__
>>> dir(__future__)

Despite the magic involved with __future__, this worked; I got a list of all of the magic stuff I could enable, and easily picked 'division' out as what I wanted.

It turns out that in addition to the magic in the CPython interpreter, there is a real __future__.py module. When you import it normally you get the regular module instead of the special magic interpreter handling, and get to introspect it and so on as usual.

And talking of special magic:

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

(Other nonexistent future features get a different error message. And you specifically can't do 'from __future__ import *'.)

Written on 07 April 2006.
« Some quick SMTP connection statistics
A bash irritation »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Fri Apr 7 16:06:02 2006
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.