4 Jun, 2009
As some of you will know I've been looking at ways of simplifying web development to the point users don't need a framework at all, or can build their own. Every now and again I design some feature or another and then look around to see if there are any ways to achieve the same result with existing tools.
This week I've been looking at a way to remove the need to auto-generate projects using tools like paster create. Wouldn't it be much nicer to just copy and paste an existing project?
Well, if you design your code carefully you can, you just need to ensure that you never reference the package name in your framework or application code. Instead the package name simply becomes a config file option.
Python 2.5 supports relative imports out of the box (I thought I'd need to do some trickery like from __future__ import something but it isn't necessary). As long as all import statements in your code use relative imports everything works nicely.
Here's a demo of relative imports:
mkdir A touch A/__init__.py mkdir A/B touch A/B/__init__.py mkdir A/B/C cat << EOF > A/B/C/__init__.py from .D import message print message EOF cat << EOF > A/B/C/D/__init__.py message = "Imported module D with a relative import" EOF
Now load a Python 2.5 prompt and type this:
$ python2.5 >>> import A.B.C Imported module D with a relative import
As you can see the relative import statement in A/B/C/__init__py successfully imports the message from D so it can be printed.
See also:
Copyright James Gardner 1996-2020 All Rights Reserved. Admin.