0

I have a file somehash-mylib.py that contains, say:

def hello():
    print("hello world")

and I’d like to dynamically import this library globally (like in from mymodule import *) using only its path. Following How can I import a module dynamically given the full path? I can do it locally using:

from pydoc import importfile
module = importfile('somehash-mylib.py')

module.hello()

but I don’t know how load it globally to turn this into:

# somehow (??) load somehash-mylib.py

hello()

Any idea? Ideally I’d like the code to be simple, and make it work across multiple python versions (only the 3.x branch).

Edit As far as I can see, none of the linked answers that justified to close this question actually answer my question: I have as input only the path to the module, and I want to include it globally. Hopefully, the comment solved my issue (thanks!):

from pydoc import importfile
module = importfile('somehash-mylib.py')
locals().update(vars(module)) # make it global

# Both work now
module.hello()
hello()
3
  • 2
    try to append this to your code: locals().update(vars(module)) ; hello() Commented Jun 15, 2023 at 9:50
  • @ジョージ Awesome, seems to work perfectly! No idea which dark magic it is doing, put seems to work great! Feel free to write it as an aswer. Commented Jun 15, 2023 at 9:55
  • 2
    I've reopened your question, please move the answer into an answer. You can ping gold badge holders who close your questions as duplicates. Commented Jun 15, 2023 at 10:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.