Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AI and Deep Learning by (50.2k points)

When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.

So I have this .py file that reads like:

starting_length=9

starting_cell_size=1000

LengthofExperiments=5000000

Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.

I can also write a similar file very easily:

def writeoptions(directory):

    options=""

    options+="starting_length=%s%s"%(starting_length,os.linesep)

    options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)

    options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)

...

    open("%s%soptions.py"%(directory,os.sep),'w').write(options)

I want to pass a function as one of the parameters:

starting_length=9

starting_cell_size=1000

LengthofExperiments=5000000

def Pippo(a,b):

    return a+b

functionoperator=pippo

And of course in the real experiment the function Pippo will be much more complex. And different from experiment to experiment.

But what I am unable to do is to write the function automatically. In short, I don't know how to generalize the write options function to keep on writing the options, if one of the options is a function. I could, of course, copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.

How do you get python to write down the code of a function, as it writes down the value of a variable?

1 Answer

0 votes
by (108k points)

Instead of just diving into the topic of disassemblers and bytecodes (e.g inspect), why don't you just preserve the generated Python source in a module (file.py), and later, import it?

I would recommend looking into a more standard way of handling what you describe options. For example, you can use the JSON module and save or restore your data. Or look into the marshal and pickle modules.

You can refer to the following link for more information about How do you get Python to write down the code of a function it has in memory: https://code-examples.net/en/q/61a77

Browse Categories

...