6

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?

4
  • you can use @staticmethod and class variables if you only need one instance
    – JBernardo
    Commented Sep 13, 2011 at 1:20
  • @JBernardo You can't use staticmethod and class variables, you can use classmethod and class variables. That's a poor way to create a singleton though.
    – agf
    Commented Sep 13, 2011 at 2:32
  • @agf I know it looks like the java's (bad) way of life... but it's not so bad.
    – JBernardo
    Commented Sep 13, 2011 at 2:39
  • You still mess up subclassing if you refer to the class by name from staticmethods instead of using the automatically passed reference to the class from classmethods.
    – agf
    Commented Sep 13, 2011 at 2:42

2 Answers 2

7

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.

4

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.

2
  • 4
    Even if for some reason you really do want the class to be private, you still should just lowercase for the instance name.
    – agf
    Commented Sep 13, 2011 at 2:34
  • Yes, because following PEP8 makes other Python developer's brains hurt less. Commented Sep 13, 2011 at 2:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.