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

accessing a classes code

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
11 1509
"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
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
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
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
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
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
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
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
> 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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Daniel Corbett | last post by:
I am trying to save a file dynamically created in a webpage. I get the following headers, but cannot figure out how to save the attachment. I am basically trying to replicate what internet...
1
by: jimfollett1 via DotNetMonster.com | last post by:
Hey all, I was wondering if you could put me out of my misery (hopefully, not literaly) .. I am currently trying to port some VB6 code to VB.NET because of a possible significant performance...
1
by: Stephan Zaubzer | last post by:
Hi I relatively new to C# and at the moment I am having troubles accessing com objects within C#. I am working in VS.net. I add the com library I want to access to my references. Accessing...
5
by: Cyril Gupta | last post by:
Hello, I have a class inside another class. The Scenario is like Car->Engine, where Car is a class with a set of properties and methods and Engine is another class inside it with its own set of...
2
by: Jimmy Reds | last post by:
Hi, I have a blood glucose meter (a Lifescan OneTouch Ultra in case anyone was wondering) which I connect to my PC using a USB cable and I would like to have a go at accessing the data on this...
3
by: eholz1 | last post by:
Hello php group, I have a dev server running php 5.0 and apache 2.2, I have created some php files that create classes, etc All works well with this. But when I copy the files to my hosting...
4
by: GesterX | last post by:
Hi guys, this has been bugging me for a while and I'd appreciate any help anyone could offer. Basically I am running a boating simulation and I have all of the "harder" parts done but one error is...
3
by: djsuson | last post by:
I'm trying to set up an inheritance tree that also uses templates. This is an attempt to simplify some previous code that was filled with redundancies. I'm working with g++ 3.4.6. The code is split...
9
by: fgh.vbn.rty | last post by:
Say I have a base class B and four derived classes d1, d2, d3, d4. I have three functions fx, fy, fz such that: fx should only be called by d1, d2 fy should only be called by d2, d3 fz should...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.