TulkinRB
TulkinRB

Reputation: 610

python module __init__ function

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)

Upvotes: 10

Views: 21877

Answers (2)

serv-inc
serv-inc

Reputation: 38147

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.14

mymodule/__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 * 2

And 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.version

Output:

> Mymodule.two_pi = 6.28318
> Mymodule.version is 1.0

Upvotes: 2

tynn
tynn

Reputation: 39843

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)

Upvotes: 5

Related Questions