Wandering Thoughts archives

2006-04-07

A pleasing Python regularity with __future__

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 *'.)

RegularFuture written at 16:06:02; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.