0

I have a program that needs to import some classes and functions from a package by using a certain version that I have as input.

For example:

while True:
  version = input()

  if version == '1.0.0':
    import a, C from package_1_0_0
    c = C()
    a(c)
  elif if version == '1.1.0':
    import a, C from package_1_1_0
    c = C()
    a(c)
  ...

  # Unload the package loaded above to accept a new one on the next iteration
  # ...

So basically I need to load different versions of the package based on some input, load some functions and classes and unload everything waiting for the next input.

  • Read the `importlib` documentation. – tripleee Oct 15 '22 at 18:48
  • 1
    Depending on how the library itself is written, this may in fact be impossible to do *all within one Python script*. By far the most robust way to do it would be to create multiple virtual environments, and call their respective interpreters as subprocesses. – CrazyChucky Oct 15 '22 at 18:50
  • @CrazyChucky, it contains a bunch of same classes. They only differ for some internal logic. – OrsoBruno Oct 15 '22 at 19:03
  • The important gotcha isn't how different they are, it's whether any of them, anywhere in their code, use any absolute imports from themselves. If so, simply renaming the package won't be enough, and you don't want to mucking about in library code to shore up a hack. Needing to use different versions or configurations of libraries are precisely the reason virtualenvs exist; that's basically what they're for. – CrazyChucky Oct 15 '22 at 19:28
  • 1
    For this approach, is https://stackoverflow.com/a/27123973/11528833 enough or do you suggest a different one? – OrsoBruno Oct 15 '22 at 19:38
  • Yes, that looks right. – CrazyChucky Oct 15 '22 at 19:41

0 Answers0