Import a module without executing it?

Caleb Hattingh caleb1 at telkomsa.net
Tue Dec 7 23:14:12 EST 2004


Andy

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

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

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,  
None))])
***

Pretty impressive :)

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

thx again
Caleb


On Tue, 7 Dec 2004 15:57:16 -0500, Andy Gross <andy at andygross.org> 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