PEP 299 and unit testing

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Oct 29 01:06:45 EDT 2007


Steven Bethard <steven.bethard at gmail.com> writes:

> Ben Finney wrote:
> > Thanks! I was unaware of that module. It does seem to nicely
> > address the issue I discussed.
> 
> You might try the runpy module as-is with Python 2.4.  I don't know
> if it works, but it's pure Python so it's worth a try.

Drat. It uses (by explicit design) "the standard import mechanism" to
load the module, which means it doesn't work for exactly the thing I'm
trying to do: load a program file *not* named with a '.py' suffix.

I've long been able to load my program modules from no-suffix
filenames (or indeed any non-standard filenames) with this function::

    def make_module_from_file(module_name, file_name):
        """ Make a new module object from the code in specified file """

        from types import ModuleType
        module = ModuleType(module_name)

        module_file = open(file_name, 'r')
        exec module_file in module.__dict__
        sys.modules[module_name] = module

        return module

Unfortunately, it seems that "module is already present with name
'foo' in 'sys.modules'" is insufficient for the Python import
mechanism. The module loader used by 'runpy' still complains that it
can't find the module, which is no surprise because its filename is
not that of a library module.

Perhaps I need to delve into the details of the import mechanism
myself :-(

-- 
 \        "With Lisp or Forth, a master programmer has unlimited power |
  `\     and expressiveness. With Python, even a regular guy can reach |
_o__)                            for the stars."  -- Raymond Hettinger |
Ben Finney



More information about the Python-list mailing list