Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection in python (dependend on module availability)

I am working on plugin for GPS IDE, and I would like to have two versions of it: 1. GPS plugin - run with GPS 2. Standalone app - run without GPS

One of plugin's features is line highlighting. When plugin is run as standalone app it is impossible. I created gpshelper class for that, which imports GPS module. Import throws ImportException when running as standalone app (because GPS module is not available). I wonder how I should inject this gpshelper module to my plugin.

Highlighting is performed during highlight method call (this method call gpshelper).

Is it ok, when inside highlight method I do this:

try:
    import gpshelper
except ImportError:
    warnings.warn('Program is running as python app (not GPS plugin)')

Maybe there is some other/better way how to do that?

like image 428
Jacob Jedryszek Avatar asked Dec 07 '25 09:12

Jacob Jedryszek


1 Answers

Define a gps_highlight routine as part of the try part importing gpshelper. Then call that routine from your existing code. In the except part define a dummy gps_highlight function. That way you keep your calling code clean:

import warnings

try:
    import gpshelper
    def gps_highlight(*args, **kw):
        return gpshelper.highlight(*args, **kw)
except ImportError:
    warnings.warn('Program is running as python app (not GPS plugin)')
    def gps_highlight(*args, **kw):
        return None

# after this you can safely call gps_highlight with the right parameters
# as needed by gpshelper.highlight
like image 50
Anthon Avatar answered Dec 10 '25 04:12

Anthon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!