Use module as class instance in Python
<h2>TL; DR</h2>

<p>Basically the question is about hiding from the user the fact that my modules have class implementations so that the user can use the module as if it has direct function definitions like <code>my_module.func()</code></p>

<h2>Details</h2>

<p>Suppose I have a module <code>my_module</code> and a class <code>MyThing</code> that lives in it. For example:</p>

<pre><code># my_module.py

class MyThing(object):
    def say():
        print("Hello!")
</code></pre>

<p>In another module, I might do something like this:</p>

<pre><code># another_module.py

from my_module import MyThing

thing = MyThing()
thing.say()
</code></pre>

<p>But suppose that I don't want to do all that. What I really want is for <code>my_module</code> to create an instance of MyThing automatically on <code>import</code> such that I can just do something like the following:</p>

<pre><code># yet_another_module.py

import my_module

my_module.say()
</code></pre>

<p>In other words, whatever method I call on the module, I want it to be forwarded directly to a default instance of the class contained in it. So, to the user of the module, it might seem that there is no class in it, just direct function definitions in the module itself (where the functions are actually methods of a class contained therein). Does that make sense? Is there a short way of doing this?</p>

<p>I know I could do the following in <code>my_module</code>:</p>

<pre><code>class MyThing(object):
    def say():
        print("Hello!")

default_thing = MyThing()

def say():
    default_thing.say()
</code></pre>

<p>But then suppose <code>MyThing</code> has many "public" methods that I want to use, then I'd have to explicitly define a "forwarding" function for every method, which I don't want to do.</p>

<p>As an extension to my question above, is there a way to achieve what I want above, but also be able to use code like <code>from my_module import *</code> and be able to use methods of <code>MyThing</code> directly in another module, like <code>say()</code>? </p>

<p>In module <code>my_module</code> do the following:</p>

<pre><code>class MyThing(object):
    ...

_inst = MyThing()
say = _inst.say
move = _inst.move
</code></pre>

<p>This is <em>exactly</em> the pattern used by the <a href="https://github.com/python/cpython/blob/master/Lib/random.py#L736" rel="nofollow"><code>random</code> module</a>.</p>

<p>Doing this automatically is somewhat contrived. First, one needs to find out <em>which</em> of the instance/class attributes are the methods to export... perhaps export only names which do not start with <code>_</code>, something like</p>

<pre><code>import inspect
for name, member in inspect.getmembers(Foo(), inspect.ismethod):
    if not name.startswith('_'):
        globals()[name] = member
</code></pre>

<p>However in this case I'd say that explicit is better than implicit.</p>

python class module