473,586 Members | 2,639 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic class/module use? (like Java's forName)

Does python provide a way to dynamically use modules and/or classes?
I'm thinking in the vein of Java's Class.forName.

As a pseudocode example, I'm looking for the following ability:
classIWantToIns tantiate = "packagenameher e.classNameHere "

anInstanceOfTha tClass = makeNewClassFro mString(classIW antToInstantiat e,
parameters[])

# now anInstanceOfTha tClass refers to an instantied
# packagenamehere .classNameHere object!

thanks
alex
Jul 18 '05 #1
14 2144
Alex Hunsley wrote:
Does python provide a way to dynamically use modules and/or classes?
I'm thinking in the vein of Java's Class.forName.

As a pseudocode example, I'm looking for the following ability:
classIWantToIns tantiate = "packagenameher e.classNameHere "

anInstanceOfTha tClass = makeNewClassFro mString(classIW antToInstantiat e,
parameters[])

# now anInstanceOfTha tClass refers to an instantied
# packagenamehere .classNameHere object!

thanks
alex


Oops.. I goggled but not hard enough obviously! I found my answer on
google groups:

http://shorterlink.com/?N2HPGU

alex
Jul 18 '05 #2
In article <_O************ *****@fe2.news. blueyonder.co.u k>,
Alex Hunsley <la**@tardis.ed .ac.molar.uk> wrote:
Does python provide a way to dynamically use modules and/or classes?
I'm thinking in the vein of Java's Class.forName.


Just out of curiosity, why do you want to do that?

The google link you provided talked about eval and exec. My experience
is that when I first started using Python (about 7 years ago), I used
eval and exec a lot. Now, I can't remember the last time I ever wanted
to use either.

Can you give us an example of what you're trying to do? My guess,
having not yet seen it, is that there's probably a better way to do it
than what you're asking.
Jul 18 '05 #3
On Sat, 17 Jul 2004 18:00:26 GMT, rumours say that Alex Hunsley
<la**@tardis.ed .ac.molar.uk> might have written:
Does python provide a way to dynamically use modules and/or classes?
I'm thinking in the vein of Java's Class.forName.


[snip]

Have you already considered the 'new' module? If not, give it a try.
--
TZOTZIOY, I speak England very best,
"Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek
Jul 18 '05 #4
Roy Smith wrote:
In article <_O************ *****@fe2.news. blueyonder.co.u k>,
Alex Hunsley <la**@tardis.ed .ac.molar.uk> wrote:

Does python provide a way to dynamically use modules and/or classes?
I'm thinking in the vein of Java's Class.forName.

Just out of curiosity, why do you want to do that?

The google link you provided talked about eval and exec. My experience
is that when I first started using Python (about 7 years ago), I used
eval and exec a lot. Now, I can't remember the last time I ever wanted
to use either.

Can you give us an example of what you're trying to do? My guess,
having not yet seen it, is that there's probably a better way to do it
than what you're asking.


Ok, the situation is that I am parsing a file that has "actions" (or
commands) embedded in it. Different actions cause different things to
happen to the file which is being preprocessed for something. Now, since
I will have many actions, and want my python to be extensible so other
users can add their own actions, rather than hard coding each action
like so:

if (actionString == "blah"):
blahThang = blah(constructo r stuff)
blahThang.doSom ething()
else if (actionString == "blah2"):
blahThang2 = blah2(construct or stuff)
blahThang2.doSo mething()
else if (actionString == "blah3"):
blahThang3 = blah3(construct or stuff)
blahThang3.doSo mething()
else if (actionString == "blah2"):
# etc etc

.... I can have a different python class (and hence source file) for each
action, and the code for launching an action becomes generic (i.e.
creates instance of the class based on the command string and calls
agreed methods on it). I prefer this to the altyernative of hardcoding
each action with an 'if', as above, and then getting another user who
wants to extend my project have to add yet another if clause as well as
some code.
Another advantage of this generic approach is that it encourages other
users extending my code to put actions in seperate files, one per
action, rather than adding 'magic' code into the above 'if' chaos.

Basically, modular actions is the idea!

I'd be keen to hear peoples thoughts on my approach.

thanks
alex


Jul 18 '05 #5
Roy Smith wrote:
In article <_O************ *****@fe2.news. blueyonder.co.u k>,
Alex Hunsley <la**@tardis.ed .ac.molar.uk> wrote:

Does python provide a way to dynamically use modules and/or classes?
I'm thinking in the vein of Java's Class.forName.

Just out of curiosity, why do you want to do that?


p.s. to my last response:

I've just read Robert Brewer's reply, and to rephrase myself as I to
him: I'm trying to do the strategy pattern in a modular fashion. (i.e.
no big string of 'ifs' and hardcoded actions.)

alex
Jul 18 '05 #6

"Alex Hunsley" <la**@tardis.ed .ac.molar.uk> wrote in message
news:8g******** **********@fe2. news.blueyonder .co.uk...

if (actionString == "blah"):
blahThang = blah(constructo r stuff)
blahThang.doSom ething()
else if (actionString == "blah2"):
blahThang2 = blah2(construct or stuff)
blahThang2.doSo mething()
else if (actionString == "blah3"):
blahThang3 = blah3(construct or stuff)
blahThang3.doSo mething()
else if (actionString == "blah2"):
# etc etc


The Python idiom for something like the above is to use a dict instead of
if/else.
It is especially useful when you want to add alternatives at runtime.
Something like

actions = { 'blah':blah, 'blah2', blah2, 'blah3':blah3, ...}
# easily extended at runtime
....
actions[actionString](constructor_st uff).doSomethin g

Terry J. Reedy

Jul 18 '05 #7
"Alex Hunsley" <la**@tardis.ed .ac.molar.uk> wrote in message
news:8g******** **********@fe2. news.blueyonder .co.uk...
<snip>
Ok, the situation is that I am parsing a file that has "actions" (or
commands) embedded in it. Different actions cause different things to
happen to the file which is being preprocessed for something. Now, since
I will have many actions, and want my python to be extensible so other
users can add their own actions, rather than hard coding each action
like so:

if (actionString == "blah"):
blahThang = blah(constructo r stuff)
blahThang.doSom ething()
else if (actionString == "blah2"):
blahThang2 = blah2(construct or stuff)
blahThang2.doSo mething()
else if (actionString == "blah3"):
blahThang3 = blah3(construct or stuff)
blahThang3.doSo mething()
else if (actionString == "blah2"):
# etc etc

<snip>

Alex,

Have a look at how pyparsing (http://pyparsing.sourceforge.net) supports the
attachment of actions to parse expressions within a grammar.

-- Paul
Jul 18 '05 #8
Roy Smith <ro*@panix.co m> writes:

Just out of curiosity, why do you want to do that?


in order to be more flexible,
allowing code to be integrated that is available
only at run time of the program

Klaus Schilling
Jul 18 '05 #9
Terry Reedy wrote:
"Alex Hunsley" <la**@tardis.ed .ac.molar.uk> wrote in message
news:8g******** **********@fe2. news.blueyonder .co.uk...
if (actionString == "blah"):
blahThang = blah(constructo r stuff)
blahThang.doSom ething()
else if (actionString == "blah2"):
blahThang2 = blah2(construct or stuff)
blahThang2.doSo mething()
else if (actionString == "blah3"):
blahThang3 = blah3(construct or stuff)
blahThang3.doSo mething()
else if (actionString == "blah2"):
# etc etc

The Python idiom for something like the above is to use a dict instead of
if/else.
It is especially useful when you want to add alternatives at runtime.
Something like

actions = { 'blah':blah, 'blah2', blah2, 'blah3':blah3, ...}
# easily extended at runtime
...
actions[actionString](constructor_st uff).doSomethin g

Terry J. Reedy


Interesting, I hadn't thought of using a dict.
Using a dict would be better than 'if's, but would still require a
central part of the code to know about all the actions!
My way allows new classes to be presented and used without altering
existing code.
Also my method forces new actions to interface with 'central' code via
the available official interface, rather than having new actions
potentially put in the central code and hence have access to things
directly (which isn't a good OO design).

Jul 18 '05 #10

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

Similar topics

2
23151
by: Roger Vandervort | last post by:
I've leafed through the docs and user comments on php.net, but haven't been able to find anything related to this. Is there a way to dynamically instantiate a class, like you can in Java with class.forName() ? example: $myclass = "Automobile"; $func = "drive";
8
10833
by: Fu Bo Xia | last post by:
the java.lang.Object.forName method takes a java class name and returns a Class object associated with that class. eg. Class myClass = Object.forName("java.lang.String"); by if i only know the absolute file name of a .class file eg. C:\myJava\myApp.java, then how do i translate this file name to a java class name the Object.forName method...
2
21921
by: Vijay Singh | last post by:
How do you instantiat a class with a Class.forName( ) method, if the class's default constructor requires a parameter?
3
1950
by: Jeff Poste | last post by:
Hi, I'm developing software that requires business rules that constantly need new versions for different quarters, years, etc. I created a business rule factory that stores these different business rules in a hashtable indexed by the year, ie "3Q2003". Now based upon the key that I give the factory, it will return a reference to the...
2
2428
by: jean-francois | last post by:
In java you can do it with Class.forName("myClass").newInstance(); this will return you a new instance of the class myClass, provided that you defined it elsewhere. How can I get this in c++ (linux)? For exemple I'm fetching elements from a vector, they are all subclasses of a base class Field, but the data type within each subclass can vary...
4
7067
by: PaperPilot | last post by:
I have a Java program that is deployed as a .jar file in which is another .jar file with the mysql library. Here is the appropriate section of code: /** * Makes the connection to the database. */ protected static Connection makeConnection() { try { Class.forName("org.gjt.mm.mysql.Driver");
4
2127
by: vasavimaruthi | last post by:
hi, i got class not found exception of a small jdbc program in windows. the program is like this import java.sql.*; public class Db1 { public static void main(String a) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver");
6
9414
by: robtyketto | last post by:
Greetings, Im a newbie to JSP/Javascript (unfortunalley). However I found enough example to create code that connects to my access db and populates two combo boxes. The selection of the first box is used to populate the second (cascading). See code below, apologies for the formatting as I wrote it in notepad. I am assuming the code...
0
2073
by: asti1987 | last post by:
I have a big problem, y need to print a jasper report, but it must to be with jsp. this is my jsp please help me <%@ page import="java.io.*,java.util.*,java.net.*,java.sql.*,imprimir.imprimir" %> <%
0
7912
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7839
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...
0
8202
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
6614
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...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5390
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3837
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...
0
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
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

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.