Dynamic class creation - Python
<p>Here is the scenario:</p>

<p>I have two classes:</p>

<pre><code>class A:
  pass:

class B:
  pass
</code></pre>

<p>Now I want to create a client, in that I need to have a small utility method, which should return my class template/object e.g: class A, class B, as I pass on the class name to that utility e.g <code>get_obj(classA)</code>.</p>

<p>Now, is this possible? If then please suggest an approach, as I don't get any correct answer as of now in web.</p>

<p>Hope I am making sense.</p>

<p><code>globals()</code> returns a dictionary containing all symbols defined in the global scope of the module (including classes <code>A</code> and <code>B</code>):</p>

<p><em>a_and_b_module.py</em></p>

<pre class="lang-py prettyprint-override"><code>class A: pass
class B: pass

def get_cls(cls_name):
    return globals()[cls_name]
</code></pre>

<p><strong>If you are looking for simplicity</strong></p>

<p>If the code that will call this function is inside the module, then you can eliminate the function altogether and use <code>globals()[cls_name]</code> directly.</p>

<p>If the code that will call this function is outside the module, then you could use <code>getattr</code> function:</p>

<p><em>a_and_b_module.py</em></p>

<pre class="lang-py prettyprint-override"><code>class A: pass
class B: pass
</code></pre>

<p><em>another_file.py</em></p>

<pre class="lang-py prettyprint-override"><code>import a_and_b_module

cls_name = 'A'
chosen_cls = getattr(a_and_b_module, cls_name)
</code></pre>

<p><strong>If you are looking for complete control</strong></p>

<p>The problem with the approach above is that it could return anything defined in <em>a_and_b_module.py</em>, not restricting itself to <code>A</code> and <code>B</code>. If you want to make sure only A and B can be returned:</p>

<pre class="lang-py prettyprint-override"><code>class A: pass
class B: pass

allowed_classes = ('A', 'B')

def get_cls(cls_name):
    assert cls_name in allowed_classes
    return globals()[cls_name]
</code></pre>

<p>Note: you might also be interested in the concept of <a href="https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)" rel="nofollow">factory</a>.</p>

python oop inheritance