Search code examples
pythonpython-2.7initializationclass-method

How to setup an object before calling class methods like in Java/Spring?


I have an object that needs to be initialised by reading a config file and environment variables. It has class methods, I want to make sure the object is initialised before the classmethod is executed.

Is there any way to initialise all classes of this sort of nature? I will probably have quite a few of these in my code. I'm coming from a Java/Spring background where simply putting @Service on top of the class or @PostConstruct over the initializer method would make sure it's called. If there's not a clean way to do this in normal Python, is there framework that'll make this easier?

So the class looks something like this

class MyClass(object):
    def setup(self):
        # read variables from the environment and config files

    @classmethod
    def my_method(cls, params):
        # run some code based on params and variables initialised during setup

Solution

  • You could always use a simple singleton implementation, which sounds like what you're trying to do. This post has examples of how to do it and some thoughts about whether you really need a singleton. Is there a simple, elegant way to define singletons?