Search code examples
pythonstringpython-importpython-module

How do I set the filename of a module in Python so that exceptions that occur in the module use that filename?


I'm importing modules from strings (don't ask) using the imp library. This is all working fine and dandy, but when there's an error in such a module, I get a stacktrace like this:

Traceback (most recent call last):
  File "<string>", line 33, in do_something
  File "<string>", line 20, in really_do_something
Exception: STRING FILENAME EXAMPLE

I've tried setting the file attribute on the module to something that makes sense, but the <string> filename is still used in the exception traceback.

Any ideas on how to specify the filename used in the exception?

UPDATE: I'm using imp like this: Dynamic module importing is trying to do relative imports when it shouldn't


Solution

  • The filename is set in the code objects produced by exec(). Instead of using exec() with a string, you should use compile() to compile your code separately. That way you can set the filename:

    code = compile(file_contents, '/your/filename.py', 'exec')
    exec(code, mod.__dict__)