title: Loading Custom Classes at Runtime
body: <p>I have the below code snippet which I'm trying to load in custom classes from a a directory called <code>source</code> but keep getting errors saying <code>module 'source' has no attribute 'custom_class_1_src'</code>.</p>
  <p>Folder structure:</p>
  <pre><code>main.py
  source
     +----__init__.py
     +----custom_class_1_src.py
     +----custom_class_2_src.py
  </code></pre>
  <p>Each class has the class name the same as the file with the first letter capitalised so the class names would be below, and both files have a <code>__init__</code> method in them:</p>
  <pre><code> Custom_class_1
   Custom_class_2
  </code></pre>
  <p><strong>main.py</strong></p>
  <pre><code>import os, pathlib, importlib
  
  def load_class(source, class_name):
      try:
          importlib.invalidate_caches()
          
          module = importlib.import_module('source', source)
          class_ = getattr(module, &quot;{}&quot;.format(class_name))
          instance = class_()
      except Exception as ex:
          print(ex)
  
  source_directory = str(pathlib.Path(__file__).parent.absolute()) + &quot;/source/&quot;
  sources = sorted([f for f in os.listdir(source_directory) if os.path.isfile(os.path.join(source_directory, f)) and f.endswith('_src.py')])
  
  for source in sources:
      class_name = source.replace(&quot;_src.py&quot;, &quot;&quot;).capitalize()
      
      load_class(source, class_name)
  </code></pre>
  <p><strong>custom_class_1_src.py</strong></p>
  <pre><code>class Custom_class_1:
  
      def __init__(self):
          print(&quot;found one file&quot;)
  </code></pre>