3 ms·
Putting side effects in the __init__ code seems to become quite fashionable these days but is a pretty bad idea since it removes the possibility to "just" impor
by ThePhysicist 13y ago
Putting side effects in the __init__ code seems to become quite fashionable these days but is a pretty bad idea since it removes the possibility to "just" import the functionality defined by the module without performing any initialization. Personally, I always try to avoid having a system that relies on some global configuration (like e.g. Django, Matplotlib or Flask do). In matplotlib for example this causes a lot of problems, since importing the pylab module will automatically (among other things) load and initialize a backend, which is then set in stone for the rest of the session.
IMHO, the way to go here instead is dependency injection:
Inject the configuration into the module through a function or class method (e.g. Flask.initialize({config state}). Wrapping all module functionality that depends on configuration in a class is a good idea here since it allows you to use multiple configurations in parallel and makes your code more modular.
As an example, in BlitzDB (a document-oriented database for Python, https://github.com/adewes/blitzdb https://github.com/adewes/blitzdb) there is no global configuration at all, so you can initialize and use multiple backends in parallel as you please without worrying about side effects. SQLAlchemy does it in a similar way btw.
- davmre 13y agoFYI, it is possible to call Matplotlib in an 'object-oriented' way without global state; though it's a bit more cumbersome than just using the pylab interface. See http://matplotlib.org/examples/pylab_examples/webapp_demo.html http://matplotlib.org/examples/pylab_examples/webapp_demo.ht... for an example.