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...
Having a module init function isn't unheard of. Pygame does it for the sdl initialization functions. So yes, your best bet is probably
There is no way to pass a variable at import.
Some ideas:
There are two solutions I can think of, both of which are very work-around-like solutions. The first is to ditch imports and run your script like this
The second is to put your arguments into an external temporary file, then read from that file in the dependency.
If there is only one configuration item to set, then I have found overriding the python
__builtin__
to work just fine, but it is an example of "Monkey patching" which is frowned on by some.A cleaner way to do it which is very useful for multiple configuration items in your project is to create a separate Configuration module that is imported by your wrapping code first, and the items set at runtime, before your functional module imports it. This pattern is often used in other projects.
myconfig/__init__.py :
mymodule/__init__.py :
And you can change the behaviour of your module at runtime from the wrapper:
run.py :
Output:
No you're not stuck with a module level function, it's just probably the best option. You could also use the builtin
staticmethod
orclassmethod
decorators to make it a method onsomeSclass
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.I had to do something similar for my project. If you don't want to rely on the calling script to run the initialization function, you can add your own Python builtin which is then available to all modules at runtime.
Be careful to name your builtin something unique that is unlikely to cause a namespace collision (eg
myapp_myvarname
).run.py
someClass module .py
This works well for variables that may have a default but you want to allow overriding at import time. If the
__builtin__
variable is not set, it will use a default value.Edit: Some consider this an example of "Monkey patching". For a more elegant solution without monkey patch, see my other answer.