[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

WedWonder: Scripts and Modules

In this day-and-age do you have a script in live/production-use, which 
is also a module? What is the justification/use case?

(discounting distutils and similar installation tools, or unit testing 

There are over 500 questions on StackOverflow which refer to Python's

	if __name__ == __main__:

construct. Even more if you include the idea of a main() multiple 

This construct enables code to distinguish between being "run" as a 
"script", and being imported as a "module". (which is not in question)

It intrigues me how often (per SO, quoted above) this causes anything 
from a pause to complete consternation amongst Python neophytes. In my 
own case, I accepted it as a "Pythonic" idiom, adopted its use in my 
scripts, and moved on.

Until I adopted unittest/pytest and took-on the closer definitions of 
TDD, I used to use the script/module switch as a means of testing 
modules (see also 'good, old days', below). These days, pytest requires 
a different approach and splits 'test code' from (production) "delivered 
code". Oh yeah!

However, I can't recall ever gaining similar benefit from using the 
'switch' within code designed to be a "script"!

Ages ago some beginner asked me the 'script/module switch' question, and 
I gave the standard/formulaic/Pythonic answer. However, reversing the 
question in my mind led me to ask (myself): how many scripts do I have 
(in "production use") which are ever used (also) as a module by some 
other script? I think the answer is/was: "none"! Accordingly, (spoiler 
alert: this statement may be heresy) I stopped using the "if".

Back in the ?good, old days of mainframes we wrote "monolithic" 
programs. Then we developed "modular programming" and started to split 
code into functional units, ie functions, subroutines, paragraphs, 
procedures. Thus "code re-use" was born. (see what a new idea it is! 
Subroutine libraries on mag-tape, anyone?) We distinguished a subroutine 
or "called code" (importable module in Python) from the calling-code by 
calling the latter the "main-line" (nothing to do with/say no to drugs). 
We even developed little "stub" programs; which would exercise or test 
specific subroutines to ensure that they worked (wow, how new is (much 
of) Test-Driven Development?)

So (putting nostalgia aside), these days my Python *scripts* are pure 
"main-line" code.

Faced with the perennial "main/name" question again yesterday, led me to 
review the above policy/laziness, and thus this "Wednesday Wondering":

- modules aside, how often do we write multiple-entry code these days, 
as opposed to having multiple scripts/main-lines which call re-usable 
functional modules, as-and-when?

I still don't have a single file containing a combination script/module 
amongst my applications. Do you? Why/who/how/when?