How to limit import that may throw
<p>I have a class that will normally run under Windows and uses the win32com module.  I also have a mock version of this class, both for testing and for demo purposes, which imports from the original, and should be able to run anywhere.  So, it's like this, in two files:</p>

<pre><code>import win32com.client
class basic():
    def local_instance(self):
        # called once during setup of execution
        res = win32com.client.Dispatch('Foo.Bar')
    def res_attrib(self):
        # called repeatedly by threads; must re-instantiate COM obj
        return win32com.client.Dispatch('Foo.Bar').Attribute
    def otherstuf(self):
        ...

=======================
from basic import basic

class mock(basic):
    def local_instance(self):
        res = mock_foobar()    # mock implementation with .Attribute
    def res_attrib(self):
        return res.Attribute   # mock implementation, this is OK
    # otherwise uses otherstuf() unchanged
</code></pre>

<p>The problem with this is when the mock version is loaded in an environment without win32com, the <code>import win32com.client</code> statement throws.</p>

<p>My question is, what's the correct approach to limiting the application of that import?</p>

<ul>
<li><p>embed the import inside each of the methods, where it will be executed repeatedly:</p>

<pre><code>def local_instance(self):
    import win32com.client
    res = win32com.client.Dispatch('Foo.Bar')
def res_attrib(self):
    import win32com.client
    return win32com.client.Dispatch('Foo.Bar').Attribute
</code></pre></li>
<li><p>nest the import and the def's inside a try block, where it will fail strangely if user tries to run basic in a Windows environment but doesn't happen to have win32com installed:</p>

<pre><code>try:
    import win32com.client
    def local_instance(self):
        res = win32com.client.Dispatch('Foo.Bar')
    def res_attrib(self):
        return win32com.client.Dispatch('Foo.Bar').Attribute
except:
    # alternate or no defs
</code></pre></li>
<li><p>or other?</p></li>
</ul>
