How can a Python program easily import a Python module from a file with an arbitrary name?
The standard library import mechanism doesn’t seem to help. An important constraint is that I don’t want an accompanying bytecode file to appear; if I use imp.load_module on a source file named foo, a file named fooc appears, which is messy and confusing.
The Python import mechanism expects that it knows best what the filename will be: module files are found at specific filesystem locations, and in particular that the filenames have particular suffixes (foo.py for Python source code, etc.) and no others.
That clashes with another convention, at least on Unix: files which will be executed as a command should be named without reference to the implementation language. The command to do “foo”, for example, should be in a program file named foo with no suffix.
Unit-testing such a program file, though, requires importing that file. I need the objects from the program file as a Python module object, ready for manipulation in the unit test cases, exactly as import would give me.
What is the Pythonic way to import a module, especially from a file whose name doesn’t end with .py, without a bytecode file appearing for that import?
My best implementation so far is (using features only in Python 2.6 or later):
This is a little too broad: it disables bytecode file generation during the entire import process for the module, which means other modules imported during that process will also not have bytecode files generated.
I’m still looking for a way to disable bytecode file generation for only the specified module file.