473,395 Members | 2,006 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

howto load and unload a module

Hello,

I have a directory of python scripts that all (should) contain a number of
attributes and methods of the same name.

I need to import each module, test for these items and unload the module. I have
2 questions.

1.. How do unload an imported module?
2.. how do I test for the existance of a method in a module without running it?

TIA,

Guy
Jul 19 '05 #1
7 14359
Guy Robinson wrote:
I have a directory of python scripts that all (should) contain a number
of attributes and methods of the same name.

I need to import each module, test for these items and unload the
module. I have 2 questions.

1.. How do unload an imported module?
Why would you want to? Doing what you describe doesn't require that you
"unload" a module, unless that means something more to you than, say,
merely releasing the memory used by it (which is likely insignificant to
you).
2.. how do I test for the existance of a method in a module without
running it?


The object bound to the name used in the import statement is, well, an
object, so you can use the usual tests:

import mymodule
try:
mymodule.myfunction
except AttributeError:
print 'myfunction does not exist'

or use getattr(), or some of the introspection features available in the
"inspect" module.

-Peter
Jul 19 '05 #2
Answer to 2 - ``hasattr(module, name)``

Jul 19 '05 #3

Why would you want to? Doing what you describe doesn't require that you
"unload" a module, unless that means something more to you than, say,
merely releasing the memory used by it (which is likely insignificant to
you).


Hi Peter,

I have an application with Python embedded. I'm parsing a script directory to
build a dictionary of script names with descriptions of what the scripts etc
extracted from each script. The user then selects one of these scripts to
execute by the embedded python.

Some of these scripts could potentially be quite large. Also the list of scripts
could be quite large. So the main reason for unloading modules is to save memory.

Regards,

Guy
Jul 19 '05 #4
Guy Robinson wrote:
Some of these scripts could potentially be quite large. Also the list of
scripts could be quite large. So the main reason for unloading modules
is to save memory.


Unless you're talking megabytes of bytecode (do a "wc *.pyc" on the
compiled files and see) it's probably not worth the bother.

Still, assuming the modules are pure Python, and don't do strange things
like inject references to themselves or their data into other places
(i.e. other modules, including sys or builtins), it should be possible
to unload them simply by deleting all references to them, *including*
manually removing them from sys.modules.

How do you plan to import them? Using the import statement, or
__import__, or some other means? How you do it will determine exactly
what steps are required to free them up.

Note also that this won't necessarily release any memory back to the
operating system, and it won't necessarily unload any extension modules
or other shared libraries that are loaded. The whole concept of
"unloading" a module is pretty much undefined in Python, so whatever you
can get is the best you can expect...

-Peter
Jul 19 '05 #5
Peter Hansen wrote:
Guy Robinson wrote:
I have a directory of python scripts that all (should) contain a
number of attributes and methods of the same name.

I need to import each module, test for these items and unload the
module. I have 2 questions. [snip] 2.. how do I test for the existance of a method in a module without
running it?

What the OP is calling a 'method' is more usually called a 'function'
when it is defined at module level rather than class level.


The object bound to the name used in the import statement is, well, an
object, so you can use the usual tests:

import mymodule
try:
mymodule.myfunction
except AttributeError:
print 'myfunction does not exist'

or use getattr(), or some of the introspection features available in the
"inspect" module.


Ummm ... doesn't appear to scale well for multiple modules and multiple
attributes & functions. Try something like this (mostly tested):

modules = ['foomod', 'barmod', 'brentstr', 'zotmod']
attrs = ['att1', 'att2', 'att3', 'MyString']
funcs = ['fun1', 'fun2', 'fun3']
# the above could even be read from file(s)
for modname in modules:
try:
mod = __import__(modname)
except ImportError:
print "module", modname, "not found"
continue
for attrname in attrs:
try:
attr = getattr(mod, attrname)
except AttributeError:
print "module %s has no attribute named %s" % \
(modname, attrname)
continue
# check that attr is NOT a function (maybe)
for funcname in funcs:
pass
# similar to above but check that it IS a function
BTW, question for the OP: what on earth is the use-case for this? Bulk
checking of scripts written by students?

Cheers,
John
Jul 19 '05 #6
John Machin wrote:
Peter Hansen wrote: [sample code] Ummm ... doesn't appear to scale well for multiple modules and multiple
attributes & functions.
It certainly wouldn't! :-) I was posting mainly to elicit more
information, since clearly you wouldn't get far hardcoding all the names
you were interested in. (It's hard to judge a poster's level of
expertise in Python without any example code from him. That makes it
too likely to go way above the head of the poster, and possibly provide
a much more complex solution than he really needs.)
Try something like this (mostly tested):

modules = ['foomod', 'barmod', 'brentstr', 'zotmod']
attrs = ['att1', 'att2', 'att3', 'MyString']
funcs = ['fun1', 'fun2', 'fun3']
# the above could even be read from file(s)
for modname in modules:
try:
mod = __import__(modname)
except ImportError:
print "module", modname, "not found"
continue
for attrname in attrs:
try:
attr = getattr(mod, attrname)
except AttributeError:
print "module %s has no attribute named %s" % \
(modname, attrname)
continue
# check that attr is NOT a function (maybe)
for funcname in funcs:
pass
# similar to above but check that it IS a function


Of course, one could simply hand the man a complete answer... ;-)

-Peter
Jul 19 '05 #7
BTW, question for the OP: what on earth is the use-case for this? Bulk
checking of scripts written by students?

Cheers,
John
I've embedded python in an application which has a .NET API. So users can write
scripts in python that access the .NET API. Because of the way the API works
running scripts is a 2 stage process. First you select a script from a list then
run the selected script. All scripts must therefore share a common calling
function name and I wanted to test this function existed.

I will have no idea the name or how many or how complicated the scripts will be
so it seemed a good idea to try and free up memory from the scripts that won't
be run.
(It's hard to judge a poster's level of expertise in Python without any

example >code from him.

I'm not a professional programmer so my terminology is probably confusing.It
looks like I shouldn't worry about memory issues.

Thanks for your help Peter and John,

Guy
Jul 19 '05 #8

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

Similar topics

6
by: Matthew Wells | last post by:
I am trying to load a form (load Me) without the form becoming visible. If I try me.hide or me.visible = false, they load the form and the form blinks before becoming invisible. Is there a way to...
1
by: DB2 Novice | last post by:
Hi, What are the utils provided by IBM to fast load and unload DB2 in Unix and Windows env. I read about High Performance Unload and this is just Unload, waht about Load? What is the best way...
2
by: Lauren Hines | last post by:
Hello, I have read numerous post stating that the only way to unload an assembly (DLL in my case) is to create a separate AppDomain, load the assembly, then unload it by calling AppDomain.Unload....
3
by: Daniel | last post by:
How do i dynamicaly load and unload a C# dll at runtime
2
by: brianbender | last post by:
I am trying to load and unload assemblies dynamically and call methods and properties when loaded into an Appdomain I can load assemblies all day in the current AppDomain without references and...
6
by: Andy Sutorius via DotNetMonster.com | last post by:
Using the code below the browser just sits and spins. The dll is located in the root of the web app. System.Runtime.Interop is in the using statements. I have tried this in ASP.NET 1.1 and 2.0 and...
7
by: tojigneshshah | last post by:
Hi, I am loading data from ascii delimiter file and some of the rows are getting rejected while loading. 1.0|11487.0|FQ|105061.0|332735.0|01|X.NNIE HATFIELD|1992-06-25 00:00:00|1992-...
6
by: Ronald S. Cook | last post by:
We have a Windows app that has one main form (a shell, sort of). We then load user controls into a panel on the form depending on what the user has selected. Our current code to unload the...
3
by: Johny | last post by:
Is it possible to unload a module after I've imported it. I have the main program from which I import several smaller programs. Some of these uses timeoutsocket module. But one of the smaller...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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...
0
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...
0
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,...

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.