By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,651 Members | 1,757 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,651 IT Pros & Developers. It's quick & easy.

accessing a classes code

P: n/a
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
Apr 19 '06 #1
Share this Question
Share on Google+
11 Replies


P: n/a
"Ryan Krauss" <ry*******@gmail.com> wrote in message
news:ma***************************************@pyt hon.org...
======================
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


Apr 19 '06 #2

P: n/a
Ryan Krauss wrote:
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
Apr 19 '06 #3

P: n/a
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

On 4/19/06, Paul McGuire <pt***@austin.rr._bogus_.com> wrote:
"Ryan Krauss" <ry*******@gmail.com> wrote in message
news:ma***************************************@pyt hon.org...
======================
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


--
http://mail.python.org/mailman/listinfo/python-list

Apr 19 '06 #4

P: n/a
Ryan Krauss wrote:
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...

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Apr 19 '06 #5

P: n/a
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

On 4/19/06, bruno at modulix <on***@xiludom.gro> wrote:
Ryan Krauss wrote:
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...

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'on***@xiludom.gro'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list

Apr 19 '06 #6

P: n/a
rx

"Ryan Krauss" <ry*******@gmail.com> wrote in message
news:ma***************************************@pyt hon.org...

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)[i]
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()
Apr 19 '06 #7

P: n/a
Ryan Krauss wrote:
(top-post corrected)

On 4/19/06, bruno at modulix <on***@xiludom.gro> wrote:
Ryan Krauss wrote:
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...

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.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'on***@xiludom.gro'.split('@')])"
Apr 19 '06 #8

P: n/a
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

On 4/19/06, bruno at modulix <on***@xiludom.gro> wrote:
Ryan Krauss wrote:
(top-post corrected)

On 4/19/06, bruno at modulix <on***@xiludom.gro> wrote:
Ryan Krauss wrote:

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...

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.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'on***@xiludom.gro'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list

Apr 19 '06 #9

P: n/a
> 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...

Apr 19 '06 #10

P: n/a
On 20/04/2006 6:54 AM, bruno de chez modulix en face wrote:
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...


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()
Apr 20 '06 #11

P: n/a
John Machin a écrit :
On 20/04/2006 6:54 AM, bruno de chez modulix en face wrote:
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...


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)

Apr 20 '06 #12

This discussion thread is closed

Replies have been disabled for this discussion.