python: how to import * and call imported functions when package is directory not file
if I'm developing a client-server app and have 3 files client.py, server.py, and common.py, and common.py has a useful function "normalize()", it's easy from both client and server to "from common import *; url = normalize(url)". however, if for various and strange reasons I'd rather have separate subdirectories client, server, and common, and each function have its own file, there doesn't seem to be a similar shortcut; I have to fiddle with sys.path, then after the import I need to use "url=normalize.normalize(url)". I'm sure I could program a workaround, but is there already some pythonic way of handling this that I'm unaware of?
[update: answered] here's how I did it after following Ignacio's advice:
jcomeau@intrepid:~/rentacoder/jcomeau/openid$ cat common/__init__.py; client/login.py jcomeauictx.myopenid.com import os, sys for module in os.listdir(os.path.dirname(__file__)): print >>sys.stderr, 'module: %s' % module name, extension = os.path.splitext(module) if extension == '.py' and not name.startswith('_'): importer = 'from %s import %s' % (name, name) print >>sys.stderr, 'import statement: %s' % importer exec(importer) module: __init__.py module: normalize.py import statement: from normalize import normalize module: __init__.pyc module: normalize.pyc ('http://www.myopenid.com/server', 'http://jcomeauictx.myopenid.com/')
Anything the __init__.py within the directory imports will be imported on import * provided it's not restricted by __all__.