0

main.py

from plugin import UsefulClass

worker = UsefulClass()
worker.do_your_job()

plugin.py

import missing_module

class MyPlugin(missing_module.Plugin):
  def something(self):
    print('blabla')

class UsefulClass:
  def do_your_job(self):
    print('done')

In main.py I want to import UsefulClass from plugin.py. However, plugin.py is missing dependency for other class MyPlugin.

UsefulClass doesn't have dependencies on MyPlugin class.

Is there a way to force Python import UsefulClass and ignore ImportError? I want to keep plugin.py self contained without splitting it into 2 files.

stil
  • 5,306
  • 3
  • 38
  • 44
  • [`fuckit`](https://github.com/ajalt/fuckitpy), maybe? – jonrsharpe Sep 14 '17 at 21:40
  • Take a look at [this answer I wrote for a related problem](https://stackoverflow.com/questions/45684307/get-source-script-details-similar-to-inspect-getmembers-without-importing-the/45684477#45684477). TL;DR: It monkeypatches the `__import__` function so that `import missing_module` doesn't throw an error. – Aran-Fey Sep 14 '17 at 21:43

1 Answers1

0

If you know the name of the missing module ahead of time, you could write a replacement module that contains a dummy version of the missing class and save it in the same directory as your main script (or in another directory in sys.path).

# missing_module.py
class Plugin:
    pass

The import in plugin.py should then pick up that module and be satisfied. Obviously, MyPlugin won't work.

kindall
  • 178,883
  • 35
  • 278
  • 309