Importing from __future__ doesn't work under PDB

Chris Angelico rosuav at gmail.com
Wed May 11 06:21:38 EDT 2016


On Wed, May 11, 2016 at 7:52 PM,  <martin846 at gmail.com> wrote:
> In other words, I get different results for the same expression (2/3) in the program and on the pdb prompt, which makes debugging tricky. I cannot figure out how to persuade pdb to actually load the division module. Is there an approved way? Normal modules load as expected in pdb:
>
> (Pdb) import os
> (Pdb) os.getcwd()
> '/home/martin'
>
> so this is obviously some special magic that applies only to the __future__ module. Any ideas?

You're right that future directives have special magic. I don't know
how to trigger that magic with pdb, but it doesn't surprise me that it
doesn't acknowledge future directives in the file you're debugging
(there could be multiple files - future directives apply only to that
one module).

Worst case, you should be able to hack it in like this:

# pdb_future.py
def futurize(*directives):
    import __future__
    flags = 0
    for directive in directives:
        flags |= getattr(__future__, directive).compiler_flag
    orig_compile = compile # Snapshot for closure
    def compile_future(source, filename, mode):
        return orig_compile(source, filename, mode, flags)
    return compile_future

import pdb
pdb.compile = futurize('print_function', 'division', 'absolute_import')
pdb.main()

I doubt that Python 2.7's pdb will grow a feature like this, but you
could propose it for 3.6 and see if anyone supports backporting it.
Otherwise, injecting a wrapper will work, but it ain't pretty.

ChrisA



More information about the Python-list mailing list