On Sat, 6 Mar 2021 12:00:33 +0100 Manfred Lotz <ml_n...@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() -- https://mail.python.org/mailman/listinfo/python-list