Choosable dependency

Peter Otten __peter__ at web.de
Sat Mar 6 08:06:27 EST 2021


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

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 ;)



More information about the Python-list mailing list