accessing a classes code

R

Ryan Krauss

I have a set of Python classes that represent elements in a structural
model for vibration modeling (sort of like FEA). Some of the
parameters of the model are initially unknown and I do some system
identification to determine the parameters. After I determine these
unknown parameters, I would like to substitute them back into the
model and save the model as a new python class. To do this, I think
each element needs to be able to read in the code for its __init__
method, make the substitutions and then write the new __init__ method
to a file defining a new class with the now known parameters.

Is there a way for a Python instance to access its own code
(especially the __init__ method)? And if there is, is there a clean
way to write the modified code back to a file? I assume that if I
can get the code as a list of strings, I can output it to a file
easily enough.

I am tempted to just read in the code and write a little Python script
to parse it to get me the __init__ methods, but that seems like
reinventing the wheel.

Thanks,

Ryan
 
P

Paul McGuire

======================
I have a set of Python classes that represent elements in a structural
model for vibration modeling (sort of like FEA). Some of the
parameters of the model are initially unknown and I do some system
identification to determine the parameters. After I determine these
unknown parameters, I would like to substitute them back into the
model and save the model as a new python class. To do this, I think
each element needs to be able to read in the code for its __init__
method, make the substitutions and then write the new __init__ method
to a file defining a new class with the now known parameters.

Is there a way for a Python instance to access its own code
(especially the __init__ method)? And if there is, is there a clean
way to write the modified code back to a file? I assume that if I
can get the code as a list of strings, I can output it to a file
easily enough.
======================

Any chance you could come up with a less hacky design, such as creating a
sub-class of one of your base classes? As in:

class BaseClass(object):
def __init__(self):
# do common base class stuff here
print "doing common base functionality"

class SpecialCoolClass(BaseClass):
def __init__(self,specialArg1, coolArg2):
# invoke common initialization stuff
# (much simpler than extracting lines of source code and
# mucking with them)
super(SpecialCoolClass,self).__init__()

# now do special/cool stuff with additional init args
print "but this is really special/cool!"
print specialArg1
print coolArg2

bc = BaseClass()
scc = SpecialCoolClass("Grabthar's Hammer", 6.02e23)

Prints:
----------
doing common base functionality
doing common base functionality
but this is really special/cool!
Grabthar's Hammer
6.02e+023

If you're still stuck on generating code, at least now you can just focus
your attention on how to generate your special-cool classes, and not so much
on extracting source code from running classes.

-- Paul
 
D

Diez B. Roggisch

Ryan said:
I have a set of Python classes that represent elements in a structural
model for vibration modeling (sort of like FEA). Some of the
parameters of the model are initially unknown and I do some system
identification to determine the parameters. After I determine these
unknown parameters, I would like to substitute them back into the
model and save the model as a new python class. To do this, I think
each element needs to be able to read in the code for its __init__
method, make the substitutions and then write the new __init__ method
to a file defining a new class with the now known parameters.

Is there a way for a Python instance to access its own code
(especially the __init__ method)? And if there is, is there a clean
way to write the modified code back to a file? I assume that if I
can get the code as a list of strings, I can output it to a file
easily enough.

I am tempted to just read in the code and write a little Python script
to parse it to get me the __init__ methods, but that seems like
reinventing the wheel.

Use dictionaries for those parameters, and set them on your instances.

class Foo(object):

def __init__(self, **unknown_params):
for key, value in unknown_params:
setattr(self, key, value)


HTH,

Diez
 
R

Ryan Krauss

I think this is a lot like I am planning to do, except that the new
classes will be dynamically generated and will have new default values
that I want to specify before I write them to a file. But how do I do
that?

Ryan
 
B

bruno at modulix

Ryan said:
I have a set of Python classes that represent elements in a structural
model for vibration modeling (sort of like FEA). Some of the
parameters of the model are initially unknown and I do some system
identification to determine the parameters. After I determine these
unknown parameters, I would like to substitute them back into the
model and save the model as a new python class.

Why ? Python is dynamic enough to let you modify classes at runtime...
 
R

Ryan Krauss

Because I want to store the results in one place so that in order to
use the code later, all I have to do is import the classes that
include the parameters that were previously unknown. I want to make
using the results as easy and clean as possible for other users.

Ryan
 
R

rx

Is there a way for a Python instance to access its own code
(especially the __init__ method)? And if there is, is there a clean
way to write the modified code back to a file? I assume that if I
can get the code as a list of strings, I can output it to a file
easily enough.



You are talking about writing code from and to a file. I think I had a
similar problem, because I wanted a python class to contains some persistent
runtime variables (fx the date of last backup) I didn't found a solution in
the python library so I wrote a little class myself:

import cPickle
class Persistent:
def __init__(self,filename):
self.filename=filename
def save(self):
f=file(self.filename, 'wb')
try:
for i in vars(self):
val=vars(self)
if not i[0:2]=='__':
cPickle.dump(i,f)
cPickle.dump(val,f)
finally:
f.close()
def load(self):
f=file(self.filename)
try:
while True:
name=cPickle.load(f)
value=cPickle.load(f)
setattr(self,name,value)
except EOFError:
f.close()
f.close()


You just use it like (the file has to exist - easy to change):

p=Persistent('file.obj')
p.load()
p.a=0.12345
p.b=0.21459
p.save()
 
B

bruno at modulix

Ryan Krauss wrote:
(top-post corrected)
Because I want to store the results in one place so that in order to
use the code later, all I have to do is import the classes that
include the parameters that were previously unknown. I want to make
using the results as easy and clean as possible for other users.

I'm afraid you're still thinking in terms of the solution instead of
thinking in terms of the problem to solve. The fact that classes can be
modified at runtime doesn't means that client code needs to be aware of
what happens.
 
R

Ryan Krauss

It turns out that what I want to do can be done using the inspect
module which has methods for getsourcecode among other things.

Ryan
 
B

bruno de chez modulix en face

It turns out that what I want to do can be done using the inspect
module which has methods for getsourcecode among other things.

I never said that what you wanted to do was impossible (nor even
difficult, and FWIW, there are simpler alternatives than using inspect
- using a templating system like empy comes to mind...). I only suggest
that there are possibly far better solutions, that you seem to dismiss
for some unknown reason...
 
J

John Machin

I never said that what you wanted to do was impossible (nor even
difficult, and FWIW, there are simpler alternatives than using inspect
- using a templating system like empy comes to mind...). I only suggest
that there are possibly far better solutions, that you seem to dismiss
for some unknown reason...

I'm with bruno -- IMHO, the OP's "solution" seems Byzantine, bizarre, ...

Suggestion: the initial investigator gadget writes out the discovered
parameters into a case-specific config file, whose name is later passed
as an arg to the [only one] class's __init__ method()
 
B

Bruno Desthuilliers

John Machin a écrit :
I never said that what you wanted to do was impossible (nor even
difficult, and FWIW, there are simpler alternatives than using inspect
- using a templating system like empy comes to mind...). I only suggest
that there are possibly far better solutions, that you seem to dismiss
for some unknown reason...

I'm with bruno -- IMHO, the OP's "solution" seems Byzantine, bizarre, ...

Suggestion: the initial investigator gadget writes out the discovered
parameters into a case-specific config file, whose name is later passed
as an arg to the [only one] class's __init__ method()

Suggestion: the investigator gadget is imported and called at the
top-level of the modules containing the classes, that can then access
the needed values. Then it's always possible to implement any caching
mechanism in the investigator itself.

import investigator
platform_params = investigator.investigate()

class MyObj(object):
def __init__(self):
self.attr1 = platform_params.attr1
self.attr2 = platform_params.attr2
(...)
self.attrN = platform_params.attrN

myMethod = platform_params.myMethod

def otherMethod(self, arg):
return platform_params.otherMethod(self, args)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,508
Members
48,193
Latest member
DannyRober

Latest Threads

Top