organizing your scripts, with plenty of re-use
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Oct 12 18:34:49 EDT 2009
En Mon, 12 Oct 2009 15:24:34 -0300, Buck <workitharder at gmail.com> escribió:
> On Oct 10, 9:44 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> The good thing is that, if the backend package is properly installed
>> somewhere in the Python path ... it still works with no modifications.
>
> I'd like to get to zero-installation if possible. It's easy with
> simple python scripts, why not packages too? I know the technical
> reasons, but I haven't heard any practical reasons.
>
> If the reasons are purely technical, it smells like a PEP to me.
That's what I meant to say. It IS a zero-installation schema, and it also
works if you properly install the package. Quoting Steven D'Aprano
(changing names slightly):
"""You would benefit greatly from separating the interface from
the backend. You should arrange matters so that the users see something
like this:
project/
+-- animal
+-- mammal
+-- reptile
+-- somepackagename/
+-- __init__.py
+-- animals.py
+-- mammals/
+-- __init__.py
+-- horse.py
+-- otter.py
+-- reptiles/
+-- __init__.py
+-- gator.py
+-- newt.py
+-- misc/
+-- __init__.py
+-- lungs.py
+-- swimming.py
where the front end is made up of three scripts "animal", "mammal" and
"reptile", and the entire backend is in a package.""" [ignore the rest]
By example, the `animal` script would contain:
from somepackagename import animals
animals.main()
or perhaps something more elaborate, but in any case, the script imports
whatever it needs from the `somepackagename` package.
The above script can be run:
a) directly from the `project` directory; this could be a checked out copy
from svn, or a tar file extracted in /tmp, or whatever. No need to install
anything, it just works.
b) alternatively, you may install somepackagename into site-packages (or
the user site directory, or any other location along the Python path), and
copy the scripts into /usr/bin (or any other location along the system
PATH), and it still works.
The key is to put all the core functionality into a package, and place the
package where Python can find it. Also, it's a good idea to use relative
imports from inside the package. There is no need to juggle with sys.path
nor even set PYTHONPATH nor import __main__ nor play any strange games; it
Just Works (tm).
--
Gabriel Genellina
More information about the Python-list
mailing list