Division oddity

Andrew Clover and-google at doxdesk.com
Mon Jan 12 17:52:06 CET 2004

Raymond Hettinger <python at rcn.com> wrote:

> So, the way to get eval() to respond to the import is to pass along
> the current environment:

> >>> from __future__ import division
> >>> eval('9/2', globals())
> 4.5

You can also put a future-import in the string, allowing you to run code
with features not known until run-time (and without affecting the host
script). Of course the catch is that import is a statement, not an
expression, so you have to do it with 'exec', eg.:

  expr= '9/2'
  features= 'division'
  scope= {}
  exec 'from __future__ import %s\n__assign= (%s)'%(features,expr) in scope
  print scope['__assign']


What you then *can't* do is have a future-import in the host script without
it affecting the script in the exec block.

Python 2.2+ has a much nicer way of doing it involving passing flags to the
'compile' function, which is preferable if you don't need backwards

Anyway, straying from the original point here.

More information about the Python-list mailing list