title: How to dynamically import_module from a relative path with python importlib
body: <p>My folder structure looks like:</p>
  <pre><code>__init__.py
  core/
      fields.py
      managers.py
      models.py
      __init__.py
  models/
      products.py
      suppliers.py
      __init__.py
  </code></pre>
  <p>From class A in <code>fields.py</code> I'm trying to load class Supplier using <code>importlib.load_module</code> from which is defined in products.py or suppliers.py.  This is needed to populate some configurations in order to generate some sql.</p>
  <p>The approach below generates <code>TypeError: the 'package' argument is required to perform a relative import for '..models.suppliers.Supplier''</code>. I'm not sure how to define the package, as this isn't an installed package.</p>
  <pre><code>import importlib
  
  model_name = &quot;Supplier&quot;
  path = f&quot;...models.{model_name.lower()}s.{model_name}&quot;
  model = importlib.import_module(path)
  </code></pre>
  <p>To try and resolve this I've tried out various combination of something like below to no avail.  Error <code>ModuleNotFoundError: No module named '.core'</code> or <code>ModuleNotFoundError: No module named '.models'</code> depending on the combination of .. I'm using.</p>
  <pre><code>import importlib
  
  model_name = &quot;Supplier&quot;
  path = f&quot;...models.{model_name.lower()}s.{model_name}&quot;
  model = importlib.import_module(path, package=&quot;.core.fields&quot;)
  </code></pre>
  <pre><code>path = f&quot;{model_name.lower()}s&quot;
  model = importlib.import_module(path, package=&quot;..models&quot;)
  </code></pre>
  <p>Doesnt work either - but plainly importing <code>from ..models import Supplier</code> does.</p>
  <p>I've also tried to get python to use the absolute path.  But by using this approach, the error becomes: <code>ImportError: attempted relative import with no known parent package</code> (Referring to the imports in suppliers.py).</p>
  <p>In such case it seems to fail on the relative imports used in suppliers.py.  See below example.</p>
  <pre><code>from importlib.machinery import SourceFileLoader
  from pathlib import Path
  import os
  
  model_name = &quot;Supplier&quot;
  parent_path = Path(__file__).resolve().parent.parent
  module_path = os.path.join(parent_path, 'models', f'{model_name.lower()}s.py')
  Model = getattr(SourceFileLoader(model, module_path).load_module(), model_name)
  </code></pre>
  <p>EDIT: For completeness, throws <code>ModuleNotFoundError: No module named '.'</code>. So also a no go.</p>
  <pre><code>model = __import__(f&quot;..models.{model.lower()}.{model}&quot;)
  </code></pre>
  <p>What am I missing?</p>