organizing your scripts, with plenty of re-use

Buck workitharder at gmail.com
Mon Oct 12 18:07:38 EDT 2009


On Oct 10, 1:57 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> #!/usr/bin/python
> import os, sys
>
> if __name__ == '__main__':
>     # find out where we are, and add it to the path
>     location = __import__('__main__').__file__
>     location = os.path.dirname(location)
>     if location not in sys.path:
>         sys.path.append(location)
>
>     import animals
>     animals.main()
>
> That's not a lot of boilerplate for a script.

Does this keep working if a user decides to symlink it to their ~/
bin/? I think it doesn't (untested). Adding that capability adds a few
lines (from my boilerplate previously):
  #continue working even if the script is symlinked and then compiled
  if f.endswith(".pyc"): f = f[:-1]
  if islink(f): f = realpath(f)

My issues with boilerplate are several. It adds possible points of
bugs to the script. It's done differently by everybody, which has
various implications. The supported features are (obviously)
unstandardized. It's untested by the community and so may have bugs
even after a year or two of use.

It also violates the Don't Repeat Yourself (DRY) principle. To fix
this, I might make a packagehelper module or some such, but as soon as
I start organizing my scripts into a hierarchy (the topic of the OP),
I have a catch 22 in that packagehelper is a module that helps me find
modules. This means I need a copy of packagehelper in each script
directory, again violating DRY.

There's a couple other things, but I'll stop myself here.
--Buck



More information about the Python-list mailing list