3 ms·
The very first one, "Make a script both importable and executable," needs some caveats. It's useful sometimes, but people often use it in places where it is no
by jzwinck 13y ago
The very first one, "Make a script both importable and executable," needs some caveats. It's useful sometimes, but people often use it in places where it is not a great idea. Here's why:
1) If you are in the mindset of "I want a single file which is both a library and a program," how will you name it? Files to import must end with ".py" and follow C-style name rules, so cannot start with a number cannot contain hyphens. This leads many people to break conventions when naming their programs, because on Unix, hyphens are conventional in program names but underscores are not (count the examples of each in /usr/bin on any system). And naming your program something like "2to3" is impractical if you want it to be importable also.
2) It is unclear where to install files which are both programs and libraries. Programs usually go in some sort of "bin" directory (again, on Unix systems), but libraries do not. Where do you put a file which is both?
3) Sometimes the __name__ == '__main__' trick is used to include unit tests within a module. That's not bad, but consider using Python's excellent doctest feature instead, which often serves the same need but in a richer way.
- analog31 13y agoI use the __name__ == '__main__' thing for unit testing. I don't know if this is a generally applicable technique, but a lot of my modules interact with hardware or physical measurements, so I have to "see" the results in order to believe that the units are working. Often, what I'm looking for is problems with what's actually being measured, and the effect of changing operating conditions, not just my own copious programming bugs. For this reason, my unit tests can be pretty elaborate, with GUI, graphs, and other stuff. The unit test also functions as a "demo" of the module.
- jzwinck 13y agoAbsolutely--that's a great example of a library module that may also be usefully executed. I had something similar today: a module that sends email. It's useful to be able to run it (by explicit "python foo.py", not chmod +x) and see a sample email in my inbox. Unfortunately, for every good use of this trick, there seem to be two poor ones. Oh well. Most of the things in TFA are more generally applicable.