[Python-Dev] Single .py file contains submodule?

Kevin Butler kbutler@campuspipeline.com
Thu, 30 May 2002 16:23:44 -0600


Guido wrote:
 > (Barry prefers that there's only one class per file; fortunately I
 > don't have that hangup. :-)

So how about a single .py file containing a module and one-or-more submodules? 
(Sounds like Barry will definitely not like it...  ;-) )

Specifically, I wanted to allow easy isolated import of the PyUnit assertion 
functions, something like:

from unittest.assertions import *

There are a few ways of refactoring unittest.py to support this, but part of 
the beauty of PyUnit is the single, independent file.

Consulting the Python Reference Manual, I couldn't find anything that forbade 
a single file from containing submodules, so I came up with the following 
implementation, which works in Jython 2.1 and Python 2.2:

import new
import sys
import types

class Assertions:
     failureException = AssertionError
     def failUnless(self, expr, msg=None):
         """Fail the test unless the expression is true."""
         if not expr: raise self.failureException, msg
     #...

def __publishAsModule( name, dict ):
     submodule = new.module( name )
     submodule.__dict__.update( dict )
     sys.modules[ name ] = submodule
     return submodule

def __getMethods( instance ):
     methods = {}
     for name, member in instance.__class__.__dict__.items():
         if type( member ) is types.FunctionType:
             methods[name] = getattr( instance, name )
     return methods

assertions = __publishAsModule(
     __name__ + ".assertions",
     __getMethods( Assertions() )
     )

So, is this an egregious abuse of a regrettable oversight in the 
specification, or a reasonable way to publish multiple modules from a single 
.py file?

Thanks

kb