I'm trying to make an __init__.py file which will import all functions from *.py files from a directory into a namespace (the directory's name). The logic is shown below:
for f in os.listdir(wd):
if not f.endswith('.py') or f == '__init__.py':
continue
names = get_public_functions(open(wd + f))
try:
mod = __import__(f[:-3], fromlist=names)
for fn in names:
fun = getattr(mod, fn)
setattr(sys.modules[__name__], fn, fun)
except Exception as e:
for fn in names:
setattr(sys.modules[__name__], fn, lambda: str(e))
So, you can observe that if there are syntax error in a file, the functions will still be imported, but they will return the syntax error (as a string).
What's frustrating, is that when there are syntax errors in multiple files, while I'm expecting something like:
mymodule.fn() => error1,
mymodule.fn2() => error1 (these were from the first file),
mymodule.fn3() => error2 etc.
I get only the last error message. I think the error must be in the except block, but I can't figure it. Can anyone help?