Dzawor Dzawor - 25 days ago 6x
Python Question

Initializing many objects in an elegant way

I'm looking for a elegant way to initialize many objects.

Let's say that I have a

module, which has an interface to SVN, Git, Make and other stuff.

Currently, I'm doing it like this:

from Utils.Config import Config, Properties
from Utils.Utils import PrettyPrint, SVN, Make, Bash, Git

class Build(object):

def __init__(self):
self.config = Config()
self.make = Make()
self.env = Properties()
self.svn = SVN()
self.git = Git()
self.bash = Bash()
self.pretty_print = PrettyPrint()

and.. well, it doesn't looks good.

Is there any way to do this in more elegant way? I suppose that it can be a design problem, but I have no idea how to solve this.

I was thinking about creation
Base class
which will init all of these classes inside the
module. What do you think?


I wouldn't create a class and place it as a base, that seems like overkill, too bulky of an approach.

Instead, you could create an auxiliary, helper, function that takes self and setattr on it. An example of this with a couple of objects from collections would look like this:

from collections import UserString, deque, UserDict

def construct(instance, classes = (UserString, deque, UserDict)):
    for c in classes:
        setattr(instance, c.__name__.lower(), c([]))

Your case also fits nicely since your objects don't have some initial value required, so you can generalize and treat them in the same way :-).

Now your sample class can just call construct() with the defaults in __init__ and be done with:

class Foo:
    def __init__(self):

the construct function could of course be defined in Utils as required or, as a method in the class.