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 (e.g. normalize()), it’s easy from both client and server to do something like this:
from common import *
url = normalize(url)
However if, for various strange reasons, I’d rather have separate subdirectories (client, server, and common), and each function had 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: here’s how I did it after following Ignacio’s advice below:
$ 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)
Result:
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__.pywithin the directory imports will be imported onimport *provided it’s not restricted by__all__.