0

I have a Python module that is written like so.

SomeClasses.py
class A():
    def __init__(self):
        print "Hi! A is instantiated!"

class B():
    def __init__(self):
        print "Hi! B is instantiated!"


a = A()

When the file is imported, class A is automatically instantiated.

>>> import a
Hi! A is instantiated!

Now, most of the time, this is exactly the behavior I want. However, sometimes I do not want an entire class to be instantly created during the import because of the overhead. I did consider creating an init() function.

>>> import SomeClasses
>>> SomeClasses.init()
Hi! A is instantiated!

However, this would break most of the preexisting code. I want to avoid rewriting a lot of the existing code base. Can anyone suggest a way to tell the module upon import to not create the class?

Btw, I am running Python 2.7 on Windows 7.

Christopher Spears
  • 1,105
  • 15
  • 32
  • See [here](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Paul Rooney May 16 '16 at 23:40
  • Are you looking for `if __name__ == '__main__':`? A description can be found in this answer :http://stackoverflow.com/a/419986/1388292 – Jacques Gaudin May 16 '16 at 23:48
  • It doesn't look like this is a case for a `__name__ == '__main__'` check, considering that the questioner usually wants the initialization to happen on a regular import. – user2357112 May 16 '16 at 23:50
  • Probably not. Just checking... – Jacques Gaudin May 16 '16 at 23:53
  • You're not "creating the class" you're creating an instance. The answer to your question depends on why you create the instance, `a = A()` inside the module in the first place. Is `A` a [singleton](https://en.wikipedia.org/wiki/Singleton_pattern)? Why does `A.__init__` have so much overhead? – Bi Rico May 17 '16 at 00:15
  • Yes, A is a singleton. – Christopher Spears May 17 '16 at 17:07

1 Answers1

2

You could refactor SomeClasses and move most of it into another module:

# SomeClasses.py

# One of the few legitimate uses of import * outside of an interactive session.
from _SomeClasses import *
a = A()

# _SomeClasses.py
class A(object):
    def __init__(self):
        print "Hi! A is instantiated!"

class B(object):
    def __init__(self):
        print "Hi! B is instantiated!"

Then if you don't want the expensive initialization of a, you import _SomeClasses and use that module. The other code that relies on a existing will import SomeClasses and get the automatically-created a instance.

user2357112
  • 260,549
  • 28
  • 431
  • 505