Choosable dependency

Manfred Lotz ml_news at posteo.de
Sat Mar 6 09:06:53 EST 2021


On Sat, 6 Mar 2021 14:06:27 +0100
Peter Otten <__peter__ at web.de> wrote:

> On 06/03/2021 12:43, Manfred Lotz wrote:
> > On Sat, 6 Mar 2021 12:00:33 +0100
> > Manfred Lotz <ml_news at posteo.de> wrote:
> >   
> >> Let us say I have a package which reads a TOML file.
> >>
> >> I want to give the user of my package the choice to decide if he
> >> wants to use the toml, tomlkit or rtoml package.
> >>
> >> So, in case the user chose to use rtoml then there should be an
> >> import only for rtoml, aso.
> >>
> >> How could I achieve this?
> >>  
> > 
> > I got the following minimal example working but presumably my
> > solution isn't the best way.
> > 
> > xtoml.py:
> > 
> > class Xtoml:
> >      def __init__(self, which='rtoml'):
> >          self.which = which
> > 
> >      def parse_toml(self, toml_string):
> >          if self.which == 'rtoml':
> >              import rtoml as toml
> >          elif self.which == 'tomlkit':
> >              import tomlkit as toml
> >          else:
> >              import toml
> > 
> >          return toml.loads(toml_string)
> > 
> > 
> > test_xtoml.py:
> > 
> > from xtoml import Xtoml
> > 
> > toml_string = """
> > [default]
> > 
> > basedir = "/myproject"
> > 
> > """
> > 
> > def main():
> >      xtoml = Xtoml('toml')
> >      parsed_toml = xtoml.parse_toml(toml_string)
> >      print(parsed_toml)
> > 
> >      xtoml = Xtoml()
> >      parsed_toml = xtoml.parse_toml(toml_string)
> >      print(parsed_toml)
> > 
> > if __name__ == "__main__":
> >      main()  
> 
> As long as you use a common subset of the functions provided by the 
> packages you can just do
> 

Yes, this is a prereq. Otherwise, it wouldn't make sense to do this.


> def main():
>      global toml  # if you want to use the toml package elsewhere
>                   # in your module
> 
>      chosen_toml = ...  # get package name
>      toml = importlib.import_module(chosen_toml)
> 
>      data = toml.loads(toml_string)
> 
> However, the user usually doesn't care, so I would recommend that you
> be bold and pick the package you prefer ;)
> 

Exactly. This is why there is a default. 

Using your suggestion my minimal example now looks like follows

xtoml.py:

import importlib

class Xtoml:
    def __init__(self, which='rtoml'):
        self.toml = importlib.import_module(which)

    def parse_toml(self, toml_string):
        return self.toml.loads(toml_string)

No change in test_xtoml.py.


Thanks a lot for your help.


-- 
Manfred





More information about the Python-list mailing list