Import a module without executing it?

Caleb Hattingh caleb1 at
Wed Dec 8 05:14:12 CET 2004


thx for that.  I had a file called '' lying around, and I did:

'>>> a = compiler.parseFile('')

And "a" looks something like this:

Stmt([Import([('Tkinter', None)]), Function(None, 'add_rows', ['w',  
'titles', 'rows'], [], 0, None, Stmt([Discard(CallFunc(Getattr(Name('w'),  
'configure'), [Keyword('state', Const('normal'))], None, None)),  
For(AssName('r', 'OP_ASSIGN'), Name('rows'),  
Stmt([For(AssTuple([AssName('t', 'OP_ASSIGN'), AssName('v',  
'OP_ASSIGN')]), CallFunc(Name('zip'), [Name('titles'), Name('r')], None,  
None), Stmt([Discard(CallFunc(Getattr(Name('w'), 'insert'), [Const('end'),  
Mod((Const('%s:\t%s\n'), Tuple([Name('t'), Name('v')])))], None, None))]),  
None), Discard(CallFunc(Getattr(Name('w'), 'insert'), [Const('end'),  
Const('\n')], None, None))]), None), Discard(CallFunc(Getattr(Name('w'),  
'configure'), [Keyword('state', Const('disabled'))], None, None))])),  
Assign([AssName('app', 'OP_ASSIGN')], CallFunc(Getattr(Name('Tkinter'),  
'Tk'), [], None, None)), Assign([AssName('t', 'OP_ASSIGN')],  
CallFunc(Getattr(Name('Tkinter'), 'Text'), [Name('app'), Keyword('state',  
Const('disabled'))], None, None)), Discard(CallFunc(Getattr(Name('t'),  
'pack'), [], None, None)), Assign([AssName('info', 'OP_ASSIGN')],  
List([List([Const('Ali'), Const(18)]), List([Const('Zainab'), Const(16)]),  
List([Const('Khalid'), Const(18)])])), Discard(CallFunc(Name('add_rows'),  
[Name('t'), List([Const('Name'), Const('Age')]), Name('info')], None,  
None)), Discard(CallFunc(Getattr(Name('app'), 'mainloop'), [], None,  

Pretty impressive :)

Do you know of more batteries that can process this stuff further, for  
interest sake (and maybe the OP)?

thx again

On Tue, 7 Dec 2004 15:57:16 -0500, Andy Gross <andy at> wrote:

> You'll want to use the "compiler" package.  compiler.parseFile will  
> return an AST that you can inspect (which is not really 'reflection',  
> btw).
> /arg

More information about the Python-list mailing list