Jump to content

  • Log In with Google      Sign In   
  • Create Account

Python Dynamic Class Creation


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
7 replies to this topic

#1 tstrimple   Prime Members   -  Reputation: 1734

Like
0Likes
Like

Posted 23 April 2007 - 03:24 PM

I'm currently in the process of extending my application with python and was interested in creating python classes dynamically. I want to keep the scripting system away from using the database directly so I was going to create a class to represent each database table with properties representing the fields in a particular row. The database is created and updated based on an XML document so I'll have access to all the information I need to create the classes. I'm pretty sure that it's possible to create the classes dynamically, I've just never delved beyond the most basic python syntax. I know how to add the properties to the class once it's created, I'm not sure about the syntax for creating the class. I need to accomplish the following:
class Equipment(Table):
    pass
with just the string "Equipment". Once I get that it should be quite easy to add the methods and properties needed via Equipment.__dict__. I tried adding it to the global __dict__ map but apparently I'm not supposed to modify that one. I know I could build the string and pass it through eval but I was hoping to learn how to do it the "right" way.

Sponsor:

#2 smr   GDNet+   -  Reputation: 1681

Like
0Likes
Like

Posted 23 April 2007 - 03:53 PM

Try this

#3 mikeman   Members   -  Reputation: 2270

Like
1Likes
Like

Posted 23 April 2007 - 04:01 PM

You can use the classobj() function from the module 'new'. The first parameter is a string for the class name, the second is a tuple containing the base classes, and the third is the dictionary of the class(containing the members). Creating an empty class 'Foo' would mean:

from new import classobj
my_class=classobj('Foo',(object,),{})

And I think that, at least with the latest versions, you can just do:

my_class=type('Foo',(object,),{})

Now, if you also want to actually add a global variable named 'Foo'(which I don't consider necessarily a good practice):

globals()['Foo']=my_class

#4 tstrimple   Prime Members   -  Reputation: 1734

Like
0Likes
Like

Posted 23 April 2007 - 04:20 PM

Quote:
Original post by smr
Try this


That's a way to add a method to an instance of a class. I'm looking for a way to create a class definition dynamically. I think mikeman got exactly what I needed.

R++ to mikeman! I have already rated you up for something SMR.

And yes mikeman I was looking to add the class definition, not an instance to the globals dictionary.

#5 tstrimple   Prime Members   -  Reputation: 1734

Like
0Likes
Like

Posted 23 April 2007 - 04:39 PM

On second thought I'm not sure that's quite what I need. I would like to be able to create a script later that would look something like this.

equip = Equipment()
equip.Load(equip_id)
equip.Quantity--
equip.Save()


In which case I need the Equipment class definition available for more then just one instance. I could potentially create two instances for comparison between records. I'd rather not have to run the classobject function to create instances. It also doesn't seem like IronPython support the new module, at least as far as I can tell from google which, not surprisingly turns up a lot of false positives for the search IronPython "new module".

I would like to officially nominate 'new' as the worst possible name for a module.

#6 tstrimple   Prime Members   -  Reputation: 1734

Like
0Likes
Like

Posted 23 April 2007 - 06:27 PM

Alright, it's late and I misread things. This works.


tmp = type('Equipment',(object,),{})
globals()['Equipment'] = tmp
e = Equipment()


Why is adding Equipment to globals a Bad Thing™?

#7 Zahlman   Moderators   -  Reputation: 1682

Like
0Likes
Like

Posted 23 April 2007 - 08:30 PM

Quote:
Original post by tstrimp
Alright, it's late and I misread things. This works.


tmp = type('Equipment',(object,),{})
globals()['Equipment'] = tmp
e = Equipment()



No need for a temporary (and I hope in that case the user doesn't want a 'class tmp' :) )


def declare(classname):
globals[classname] = type(classname, (object,), {})

declare('Equipment')
e = Equipment()


(OK, so now you can't have a 'class declare'. But then, I assume you were going to want to wrap it in a function *anyway*...)

Quote:
Why is adding Equipment to globals a Bad Thing™?


Well, aside from the potential for name collision (as indicated above), I can't think of any especially good reasons.

That said, is there a reason you can't just have the scripts import some other module that defines the classes? Possibly generate that module dynamically from the database, and give it a known name so that the scripts can import it?

Also, have you considered various ways of actually running the scripts? I've found that the different semantics can be troublesome. A few times I've jumped through hoops trying to figure out how to make the script's context be what I wanted, or interact in the way I wanted with the calling context, when all I needed to was switch the way I invoked the script (in my cases, I've generally needed to use execfile()).

#8 tstrimple   Prime Members   -  Reputation: 1734

Like
0Likes
Like

Posted 24 April 2007 - 02:48 AM

Quote:
Original post by Zahlman
No need for a temporary (and I hope in that case the user doesn't want a 'class tmp' :) )


Err... I should have stopped a few hours earlier last night.

Quote:
That said, is there a reason you can't just have the scripts import some other module that defines the classes? Possibly generate that module dynamically from the database, and give it a known name so that the scripts can import it?


I could generate the the module dynamically from the xml representation of the database easy enough.

Quote:
Also, have you considered various ways of actually running the scripts? I've found that the different semantics can be troublesome. A few times I've jumped through hoops trying to figure out how to make the script's context be what I wanted, or interact in the way I wanted with the calling context, when all I needed to was switch the way I invoked the script (in my cases, I've generally needed to use execfile()).


Using execfile isn't an option currently. Right now all data files are loaded in at load time. I've extracted the concept of a file system away and instead the system is given resources. Resources for the most part are just files loaded off of the file system and passed into the application. Resources could also come from database queries, simple http requests, soap requests etc. The application doesn't know or care how that information is being loaded.

When it's loading the resources that represent the database tables it goes over them checking them against the database for changes and modifies the database to match. This is the point where the database xml resources would be passed off the the scripting engine to create the classes needed as well as the documentation for working with those classes.

Scripts are another type of resource that are loaded. They are sent to the scripting system which compiles them and loads them into the default module in a PythonEngine instance. These are the scripts which will use the database classes to build the logic for the application.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS