0

I have a program that runs through a database of objects, runs each object through a long runtime function, and then takes the output of that function to update the attributes of said object. Of course, if the function is going to return the same result (because the function's code has not changed), then we don't need to run it through the function again.

One way to solve this problem is to give the function a version number or something and check the version number against a version number stored in the object. For example, object.lastchecked=='VER2'. But this requires manually updating versions and remembering to do so.

One other, more creative way to do this would be to convert that whole function or even imported module/library into a string, hash the string, and then use that as an "automatic" version number of sorts. So if objects.lastchecked!=hash(functionconvertedtostring), we would run function(object).

What I can't figure out is how to convert an existing python module from an import line into a string. I could hardcode the path of this module and do a file read, but it's already been read once into memory. How do I get access to it?

Example:

from hugelibrary import littlefunction
for id,object in hugeobjectdb.items():
     if object.lastchecked!=hash(littlefunction):
             object.attributes=littlefunction(object)
Mr. T
  • 294
  • 2
  • 13

1 Answers1

1

There are at least 2 different ways of doing this.

First, if you use some kind of version control to work on your code, you might be able to store information about version of the module in the module file in an object that is accessible to python and that is updated automatically. Or you can use version control tools to get current version.

It might be hard to do that on the function level though, rather than file level. If it is a single function that has this requirement you might consider moving it to a separate file.

probably preferable would be to get the text of the function. for that, this answer seems to do the trick Can Python print a function definition?

Gnudiff
  • 4,297
  • 1
  • 24
  • 25