tags:

views:

42

answers:

4

Let's say you have some time-consuming work to do when a module/class is first imported. This functionality is dependent on a passed in variable. It only needs to be done when the module/class is loaded. All instances of the class can then use the result.

For instance, I'm using rpy2:

import rpy2.robjects as robjects

PATH_TO_R_SOURCE = ## I need to pass this
robjects.r.source(PATH_TO_R_SOURCE, chdir = True) ## this takes time

class SomeClass:
  def __init__(self, aCurve):
    self._curve = aCurve

  def processCurve(self):
    robjects.r['someRFunc'](robjects.FloatVector(self._curve))

Am I stuck creating a module level function that I call to do the work?

import someClass
someClass.sourceRStuff(PATH_TO_R_SOURCE)
x = someClass.SomeClass([1,2,3,4])
etc...

I gotta be missing something here. Thanks.

+2  A: 

Having a module init function isn't unheard of. Pygame does it for the sdl initialization functions. So yes, your best bet is probably

import someModule
someModule.init(NECESSARY_DATA)
x = someModule.someClass(range(1, 5))
Nathon
+1  A: 

No you're not stuck with a module level function, it's just probably the best option. You could also use the builtin staticmethod or classmethod decorators to make it a method on someSclass that can be called before it is instantiated.

This would make sense only if everything other than someClass was usable without the initialization and I still think a module level function is better.

aaronasterling
A: 

Could you benefit from a Proxy which implements lazy loading?

Check out the Active State "Lazy Module Imports" recipe.

Arrieta
+1  A: 

There is no way to pass a variable at import.

Some ideas:

  • make the module get the variable from the calling module using inspection; not very pythonic
  • use an Init function for the module, this is the best way
leoluk