Question

Is it bad practice to initialize the objects in the module, in the module code?

in Module.py:

class _Foo(object):
    def __init__(self):
        self.x = 'Foo'

Foo = _Foo()

Than in user code, you could:

>>> from Module import Foo
>>> print Foo.x
'Foo'
>>>

...without having to initialize the Foo class in the user code. Of course, only useful if you don't need arguments to initialize the object.

Is there a reason not to do this?

Was it helpful?

Solution

Typically, you only want to run the minimum necessary to have your module usable. This will have an overall effect on performance (loading time), and can also make debugging easier.
Also, usually more than one instance will be created from any given class.

Having said that, if you have good reasons (such as only wanting one instance of a class), then certainly initialize it at load time.

OTHER TIPS

I do this sometimes, when it's really convenient, but I tend to do foo = Foo(). I really dislike the idea of making the class appear private, and making the instance available as Foo. As a developer using your code I'd find that pretty disconcerting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top