kaki gadol
kaki gadol

Reputation: 1370

What is simplest way to reimport many python libraries?

I am writing a server which will run a loop over a other python scripts found in the configuration file.

the code will look somewhat like the following:

for script in CONFIG.scripts:
    import script as s
    s.some_function()
    s.another_function()

obviously every script will have to implement all the needed functions, but it must be 3rd party scripts because this is the way the users interact with the server.

what is the best way to re-import the libraries? I was thinking about few options:

  1. import script as s; importlib.reload(s)
  2. del s; import s
  3. importing all of the scripts into some list and then running over them?

Consider that the interface with the users must be as simple as possible, and I rather not enforce them doing anything more then defining the needed functions.

The server is written over python 3.6 (but it's possible to migrate it into 3.7 if it would hep this situation)

Upvotes: 0

Views: 80

Answers (1)

Simon Crane
Simon Crane

Reputation: 2182

You don't need to reload! Just import script as s will work.

Example:

a.py:

print("importing a")

def foo():
    print("foo from a")

b.py:

print("importing b")

def foo():
    print("foo from b")

main.py:

import a as c
c.foo()
import b as c
c.foo()

output:

importing a
foo from a
importing b
foo from b

Upvotes: 2

Related Questions