473,805 Members | 1,995 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Import a module without executing it?

Is there a good way to import python files without executing their content?

I'm trying some relfection based stuff and I want to be able to import a
module dynamically to check it's contents (class ad functions defined)
but without having any of the content executed.

For example:
----------------------
def test(var):
print var
#main
test(3)
----------------------

I want to be able to import this module so I can see "ah ha, this module
defines a function called 'test'", but I don't want the code at the
bottom executed during the import.

Thanks

Take care,
Jay
Jul 18 '05 #1
14 10473
Hi

You could just parse the model file. Off the top of my head

***
f = open('ModuleYou WantToExamine.p y','r')
for i in f:
if i.find('def ') > -1:
print 'Found a function!: '+i.replace('de f ','')

f.close()
***

You would have to build this up for a more complete examination. Of
course, one of the guru's around here should be able to give you guidance
regarding actually parsing the file with the interpreter (not executing)
and building a dict or something with all the different types of
constructs. That's not me :)

I want to be able to import this module so I can see "ah ha, this module
defines a function called 'test'", but I don't want the code at the
bottom executed during the import.

Thanks

Take care,
Jay


Jul 18 '05 #2

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

/arg
On Dec 7, 2004, at 10:56 PM, Caleb Hattingh wrote:
Hi

You could just parse the model file. Off the top of my head

***
f = open('ModuleYou WantToExamine.p y','r')
for i in f:
if i.find('def ') > -1:
print 'Found a function!: '+i.replace('de f ','')

f.close()
***

You would have to build this up for a more complete examination. Of
course, one of the guru's around here should be able to give you
guidance regarding actually parsing the file with the interpreter (not
executing) and building a dict or something with all the different
types of constructs. That's not me :)

I want to be able to import this module so I can see "ah ha, this
module defines a function called 'test'", but I don't want the code
at the bottom executed during the import.

Thanks

Take care,
Jay


--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #3
Andy

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

'>>> a = compiler.parseF ile('tktest.py' )

And "a" looks something like this:

***
Stmt([Import([('Tkinter', None)]), Function(None, 'add_rows', ['w',
'titles', 'rows'], [], 0, None, Stmt([Discard(CallFun c(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(CallFun c(Getattr(Name( 'w'), 'insert'), [Const('end'),
Mod((Const('%s: \t%s\n'), Tuple([Name('t'), Name('v')])))], None, None))]),
None), Discard(CallFun c(Getattr(Name( 'w'), 'insert'), [Const('end'),
Const('\n')], None, None))]), None), Discard(CallFun c(Getattr(Name( 'w'),
'configure'), [Keyword('state' , Const('disabled '))], None, None))])),
Assign([AssName('app', 'OP_ASSIGN')], CallFunc(Getatt r(Name('Tkinter '),
'Tk'), [], None, None)), Assign([AssName('t', 'OP_ASSIGN')],
CallFunc(Getatt r(Name('Tkinter '), 'Text'), [Name('app'), Keyword('state' ,
Const('disabled '))], None, None)), Discard(CallFun c(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(CallFun c(Name('add_row s'),
[Name('t'), List([Const('Name'), Const('Age')]), Name('info')], None,
None)), Discard(CallFun c(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 <an**@andygross .org> wrote:

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

/arg

Jul 18 '05 #4
Jay O'Connor wrote:
----------------------
def test(var):
print var
#main
test(3)
----------------------

I want to be able to import this module so I can see "ah ha, this module
defines a function called 'test'", but I don't want the code at the
bottom executed during the import.


If you have source control over this file, you could write it with the
more standard idiom:

def test(var):
print var

if __name__ == "__main__":
test(3)

Then when the module is imported, only the def statement gets executed,
not the 'test(3)'. Of course, if you don't have source control over the
file, you can't do this...
Also note that code that is not protected by an
if __name__ == "__main__":
test may be part of the module definition, so examining a module without
executing this code may be misleading, e.g.:

def test(var):
print var

globals()['test'] = type('C', (object,), dict(
f=lambda self, var, test=test: test(var)))

if __name__ == "__main__":
test().f(3)

The module above turns 'test' from a function into a class, so if all
you do is look at the def statements, you may misinterpret the module.

Steve
Jul 18 '05 #5
Here's a quick example that will pull out all functions defined in the
top-level of a module:

---
#/usr/bin/env python
from compiler import parse, walk
from compiler.visito r import ASTVisitor

testdata = r'''
def aFunction(anArg ):
return anArg + 1
'''
class SimpleVisitor(A STVisitor):
def visitFunction(s elf, parsedFunc):
print "Function %(name)s at %(lineno)s takes %(argnames)s " \
" with code %(code)s" % parsedFunc.__di ct__

if __name__ == "__main__":
ast = parse(testdata)
walk(ast, SimpleVisitor() , verbose=True)
---

andy@alyosha:~$ ./test.py
Function aFunction at 2 takes ['anArg'] with code
Stmt([Return(Add((Nam e('anArg'), Const(1))))])

HTH,

/arg
On Dec 7, 2004, at 11:14 PM, Caleb Hattingh wrote:
Andy

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

'>>> a = compiler.parseF ile('tktest.py' )

And "a" looks something like this:

***
Stmt([Import([('Tkinter', None)]), Function(None, 'add_rows', ['w',
'titles', 'rows'], [], 0, None,
Stmt([Discard(CallFun c(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(CallFun c(Getattr(Name( 'w'), 'insert'), [Const('end'),
Mod((Const('%s: \t%s\n'), Tuple([Name('t'), Name('v')])))], None,
None))]), None), Discard(CallFun c(Getattr(Name( 'w'), 'insert'),
[Const('end'), Const('\n')], None, None))]), None),
Discard(CallFun c(Getattr(Name( 'w'), 'configure'), [Keyword('state' ,
Const('disabled '))], None, None))])), Assign([AssName('app',
'OP_ASSIGN')], CallFunc(Getatt r(Name('Tkinter '), 'Tk'), [], None,
None)), Assign([AssName('t', 'OP_ASSIGN')],
CallFunc(Getatt r(Name('Tkinter '), 'Text'), [Name('app'),
Keyword('state' , Const('disabled '))], None, None)),
Discard(CallFun c(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(CallFun c(Name('add_row s'), [Name('t'), List([Const('Name'),
Const('Age')]), Name('info')], None, None)),
Discard(CallFun c(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 <an**@andygross .org>
wrote:

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

/arg

--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #6
Functions and classes are created during the very execution you're
trying to skip so there's no precise way to do what you want.

That said, you can parse the code without executing it, and that will
give you some information about defined functions and classes. It will
_not_ give you actual function objects; the only way to get those is to
execute the code. It will also not catch anything created "on the
fly"*, e.g. "exec 'def func(x): pass'"
# example:

def defined_functio ns(code_text):
module_ast = parse(code_text )
return [statement for statement in
module_ast.node .nodes if
isinstance(stat ement, ast.Function)]

# read the module's source code
test_string = """
def foo(x):
pass
def bar(y):
pass
"""

# Which functions are defined in the test string?
function_asts = defined_functio ns(test_string)
print "Defined functions:", [f.name for f in function_asts]


* - Okay, everything in Python happens on-the-fly. But you know what I
mean.

Footnote: Wow. The new, "improved" google groups 2 beta has totally
annihilated my indentation. Sorry about that. Hopefully you can still
figure it out.

Jul 18 '05 #7

On Dec 7, 2004, at 4:20 PM, Steven Bethard wrote:

If you have source control over this file, you could write it with the
more standard idiom...


I should have mentioned this first. If you're just trying to avoid
existing top-level code from being executed, use the if __name__ ==
"__main__" idiom.

Jul 18 '05 #8
fi************* *@gmail.com wrote:
Functions and classes are created during the very execution you're
trying to skip so there's no precise way to do what you want.
That said, you can parse the code without executing it, and that will
give you some information about defined functions and classes. It will
_not_ give you actual function objects; the only way to get those is to
execute the code. It will also not catch anything created "on the
fly"*, e.g. "exec 'def func(x): pass'"

OK, some more information on what I'm tryng to do would help.

I come from a strong Smalltalk background and in most Smalltalk IDEs is
the capability to browse "Implemento rs" (what classes implement a method
with a given name or like a given name) and "Senders" (from what methods
is a given method name called)

Given a set of code, not all of which I am familiar with, I wanted to
have similar explorative capabilities in understanding the code. grep
in Linux does a decent job, but under Windows, the file search (look for
a particular string in a py file) does not seem to be too..useful (I
don't get back the results I should)

I shied away from just hand-parsing the code because knowing that a file
has a string, or even a function with a given name, in it is not hard,
knowing that the module has a class that has the function (and knowing
the class as well) is more useful

So, in Smalltalk, the way you find out about what's in the system is
reflection...yo u ask the classes what methods they implement (if looking
for 'implementors') , you ask the methods for the source and can string
search the code (if looking for senders).

Knowing that both modules and classes (and functions) had reality enough
to be queried, that was my first line of thought, to load the module and
query the module and query the classes in the module, etc... and do
various matches against whatever I was looking for.

It worked fine for a file that just defined functions and classes.
However, files that had code not contained in classes or functions
caused a bit of a problem because loading the module would execute that
code and that's not what I wanted.

So therefore, my original question.

The real question, I suppose, is "what is a good technique to find what
modules and classes implement or refer to particular names"

Take care,
Jay
Jul 18 '05 #9
> So, in Smalltalk, the way you find out about what's in the system is
reflection...yo u ask the classes what methods they implement (if
looking for 'implementors') , you ask the methods for the source and
can string search the code (if looking for senders).
There's no real way to get the source code from a compiled code object
, although there are some tools, like decompyle, which will try for
you. I think some people on this list were discussing the potential
utility of having a __source__ attribute for code objects, but Python
currently doesn't do this. You can probably also get some mileage out
of the inspect module (try 'pydoc inspect'), but that *does* compile
the code you're inspecting.
It worked fine for a file that just defined functions and classes.
However, files that had code not contained in classes or functions
caused a bit of a problem because loading the module would execute
that code and that's not what I wanted.


To get at top-level module code like this, you'll have to parse the
file and walk the AST - there's no other way. In a well implemented
library or app, however, there typically shouldn't be much important
code being executed at the top level. Typically the top-level code
will be initialization of singleton globals or decorator-type function
wrappers, and you can get at most of the important names reflectively
through the inspect module.

/arg

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6410
by: Markus Doering | last post by:
Hello, I just switched from 2.2 to Python 2.3. I am developing an XML/CGI interface to databases as a python package called "unitWrapper" containing several modules which ran fine under v2.2. Running Python2.3 under windows2000 I get import errors when a module imports another module of the same package with absolute package-names like this:
5
1826
by: Colin Brown | last post by:
I have instances where Python 2.3.2 import both does not work or error. It can be demonstrated under Win2k and Linux by doing the following: 1. Create a subdirectory "abc" 2. In directory "abc" create a blank "__init__.py" 3. In directory "abc" create a file "abc.py" containing "print 'this is abc'" 4. Interactively run python interpreter >>> import sys >>> sys.path.append('./abc')
0
2588
by: Vio | last post by:
Hi, I've been trying to embed (statically) wxPy alongside an embedded py interpreter on a linux/gtk box. At one point, for some reason misc.o linking reported "multiple definitions of wxGetFreeMemory()". Since wxGetFreeMemory() seemed effectively unused in gtk, I just commented it out in misc_wrap.cpp (didn't want to patch SWIG to regenerate the wrapper code, so hacked the generated cpp source), and replaced...
0
1669
by: Simon John | last post by:
I have a program that consists of one main module and lots of small sub-modules. In the main module I open a text file and grep for a language setting, this language setting will then be used as the module name of a config file to import. E.g. "Language=en" means config_en.py is imported as config, "Language=fr" means config_fr.py is imported as config....
79
5301
by: pinkfloydhomer | last post by:
I want to scan a file byte for byte for occurences of the the four byte pattern 0x00000100. I've tried with this: # start import sys numChars = 0 startCode = 0 count = 0
6
2366
by: robert | last post by:
I get python crashes and (in better cases) strange Python exceptions when (in most cases) importing and using cookielib lazy on demand in a thread. It is mainly with cookielib, but remember the problem also with other imports (e.g. urllib2 etc.). And again very often in all these cases where I get weired Python exceptions, the problem is around re-functions - usually during re.compile calls during import (see some of the exceptions below). But...
5
5346
by: Roland Hedberg | last post by:
Hi! I'm having a bit of a problem with import. I'm writing a marshalling system that based on a specification will create one or more files containing mostly class definitions. If there are more than one file created (and there are reasons for creating more than one file in some instances) then they will import each other since there may be or is interdependencies in between them.
7
20578
by: Ron Adam | last post by:
from __future__ import absolute_import Is there a way to check if this is working? I get the same results with or without it. Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) on win 32 _Ron
7
2158
by: bambam | last post by:
import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global) scope. Questions: (1) Where can I read an explanation of this? (2) Is there a work around?
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10359
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10364
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10104
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9182
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5541
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4317
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.