Python class is created when module is imported
Question: 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.


Answer: 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.

