Is there any way to make an implicit initializer for modules (not packages)? Something like:
#file: mymodule.py
def __init__(val):
global value
value = 5
And when you import it:
#file: mainmodule.py
import mymodule(5)
Is there any way to make an implicit initializer for modules (not packages)? Something like:
#file: mymodule.py
def __init__(val):
global value
value = 5
And when you import it:
#file: mainmodule.py
import mymodule(5)
The import statement uses the builtin __import__ function.
Therefore it's not possible to have a module __init__ function.
You'll have to call it yourself:
import mymodule
mymodule.__init__(5)
__import__ function" and "impossibility to have __init__ function" are connected. Even your own example shows that it's totally possible to have __init__ function. But yeah, you'll need to call it yourself.import mymodule(5) which is semantically impossible. Maybe my wording was a bit off five years ago. The connection is given with the fact, that there's no mechanism to configure a module with its import.These things often are not closed as duplicates, so here's a really nice solution from Pass Variable On Import. TL;DR: use a config module, configure that before importing your module.
[...] 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 :
PATH_TO_R_SOURCE = '/default/R/source/path' OTHER_CONFIG_ITEM = 'DEFAULT' PI = 3.14mymodule/__init__.py :
import myconfig PATH_TO_R_SOURCE = myconfig.PATH_TO_R_SOURCE robjects.r.source(PATH_TO_R_SOURCE, chdir = True) ## this takes time class SomeClass: def __init__(self, aCurve): self._curve = aCurve if myconfig.VERSION is not None: version = myconfig.VERSION else: version = "UNDEFINED" two_pi = myconfig.PI * 2And you can change the behaviour of your module at runtime from the wrapper:
run.py :
import myconfig myconfig.PATH_TO_R_SOURCE = 'actual/path/to/R/source' myconfig.PI = 3.14159 # we can even add a new configuration item that isn't present in the original myconfig: myconfig.VERSION="1.0" import mymodule print "Mymodule.two_pi = %r" % mymodule.two_pi print "Mymodule.version is %s" % mymodule.versionOutput:
> Mymodule.two_pi = 6.28318 > Mymodule.version is 1.0