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

bentheiii
  • 451
  • 3
  • 15

1 Answers1

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'))
bentheiii
  • 451
  • 3
  • 15