1

I want the user to be able to write their own minimalistic script files using some values as global variables.

Basically, I want something like this:
bar.py (same directory as main.py)

def bar(x):
    return f'bar({x})'

foo.py (possibly far from main.py)

b = bar('hi') #I want bar to be a global variable in this file
def foo(x):
    return f'{x}: foo({b})'

main.py (I used Sebastian's answer on how to import modules)

import importlib.util
from bar import bar

spec = importlib.util.spec_from_file_location("", r"/path/to/foo.py") #side question: does the name parameter have any effect on the code?
fooModule = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fooModule) #<---somehow bring bar into foo's globals

print(fooModule.foo('kevin'))

Thanks in advance for any help/suggestions.

EDIT: changed the requirements to ensure bar is global at load time

1 Answer 1

2

Okay I found out the answer. It's a bit wierd but you have to set bar as a value between the loading and the excecution of foo

main.py

import importlib.util
from bar import bar

spec = importlib.util.spec_from_file_location("", r"/path/to/foo.py")
fooModule = importlib.util.module_from_spec(spec)
fooModule.bar = bar #<----
spec.loader.exec_module(fooModule)

print(fooModule.foo('kevin'))
Sign up to request clarification or add additional context in comments.

Comments

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.