473,394 Members | 1,841 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,394 software developers and data experts.

Dyanmic import of a class

Hi all,

I have a directory with a bunch of python classes each uniquely named
such that the file name (dropping .py) is also the class name of the
file in question. So for example

foo.py

class foo:
def __init__(self):
print "Hi I am %s" % self.__class__.__name__
Now I have a bunch of these files. I want to be able to dynamically
import each one and run it. I am having a problem actually doing the
work. I thought __import__ would work but I can't seem to get it to
work.

for mod in listdir():
__import__(mod)
a=mod()
a.dosomething() # This is a function which each class shares.

Can anyone help?

Mar 8 '07 #1
3 1545
On Mar 8, 9:09 pm, "rh0dium" <steven.kl...@gmail.comwrote:
[snip]
for mod in listdir():
__import__(mod)
a=mod()
a.dosomething() # This is a function which each class shares.

Can anyone help?
You are not using __import__ correctly. Perhaps reading the doc would
be a good start:
http://docs.python.org/lib/built-in-funcs.html

For example to import the module defined in 'foo.py' you would do
foo = __import__('foo')
Then your class foo would be accessible as foo.foo

HTH

--
Arnaud

Mar 8 '07 #2
Arnaud Delobelle wrote:
On Mar 8, 9:09 pm, "rh0dium" <steven.kl...@gmail.comwrote:
[snip]
>for mod in listdir():
__import__(mod)
a=mod()
a.dosomething() # This is a function which each class shares.

Can anyone help?

You are not using __import__ correctly. Perhaps reading the doc would
be a good start:
http://docs.python.org/lib/built-in-funcs.html

For example to import the module defined in 'foo.py' you would do
foo = __import__('foo')
Then your class foo would be accessible as foo.foo
To get even more explicit:
import glob, os.path
for filename in glob.glob('*.py*'):
modname, ext = os.path.splitext(filename)
try:
class_ = getattr(__import__(modname), modname)
except (ImportError, AttributeError, SyntaxError), err:
print filename, modname, err
else:
class_().dosomething()

--
--Scott David Daniels
sc***********@acm.org
Mar 9 '07 #3
rh0dium wrote:
foo.py

class foo:
def __init__(self):
print "Hi I am %s" % self.__class__.__name__
I wrote this in a file here...

Now I have a bunch of these files. I want to be able to dynamically
import each one and run it. I am having a problem actually doing the
work. I thought __import__ would work but I can't seem to get it to
work.
>>name = "foo"
mod = __import__(name)
theclass = getattr(mod, name)
instance = theclass()
Hi I am foo
Regards,

--
.. Facundo
..
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/
Mar 22 '07 #4

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

Similar topics

1
by: Chris S. | last post by:
Consider the sample case: ## a.py import d import b b.App() ## b.py from c import C B = 'B'
1
by: Andrew James | last post by:
All, I'm having some trouble with understanding python's importing behaviour in my application. I'm using psyco to optimise part of my code, but I'm not sure whether it inherits throughout the...
2
by: Tian | last post by:
I am writing a python program which needs to support some plug-ins. I have an XML file storing some dynamic structures. XML file records some class names whose instance needs to be created in the...
0
by: Bill Davy | last post by:
I am working with MSVC6 on Windows XP. I have created an MSVC project called SHIP I have a file SHIP.i with "%module SHIP" as the first line (file is below). I run SHIP.i through SWIG 1.3.24...
2
by: Egbert Nierop \(MVP for IIS\) | last post by:
Hi, I use the llib library from adler and compiled it myself. First I build the lib configuration, then I included zlib.h in stdafx.h and I added a lib reference...
9
by: Peter Olcott | last post by:
// // Array2D.h 2005-11-27 5:50 AM // #define UINT unsigned int // // // class ArrayType2D { private: int Width;
11
by: Brian Blazer | last post by:
OK, I have a very simple class here: class Student: """Defines the student class""" def __init__(self, lName, fName, mi): self.lName = lName self.fName = fName self.mi = mi
2
by: Panard | last post by:
Hi, I'm experiencing a strange problem while trying to manage a ftp connection into a separate thread. I'm on linux, python 2.4.3 Here is a test : ------ ftp_thread.py ------ import ftplib...
1
by: pupilstuff | last post by:
hi guys i wan to make dyanmic crystal report according to values which i checked from check box thats all i did 1. I made data set having data table name "Customer" 2 i put four columm id,name...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...

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.