[Tutor] creating objects in a loop
Erik Price
erikprice@mac.com
Wed, 3 Apr 2002 07:32:52 -0500
On Tuesday, April 2, 2002, at 11:22 PM, Kirby Urner wrote:
> or do that same import at the top of some *other* module, then
> the __name__ = '__main__' condition won't be true, and no code
> will actually execute, which is good, because when I import this
> way, I'm not supplying arguments to any function and I don't want
> to actually generate a sinewave. I'll maybe do that later, by invoking
> an internal function explicitly.
I see. It hadn't crossed my mind that you might have a script that is
useful both as an executable and as a library of code. So this test
lets you put executable code into a "protected" area that only runs if
the script is run as a script, and not imported (because an import will
automatically execute all code that is -not- protected in this fashion,
won't it). I understand now.
> The __name__ = '__main__' code block is sometimes used to
> write tests of the module's main functions. This is in cases where
> the module is really designed to function as a module. The only
> reason you'd run it as a standalone script is precisely to invoke
> these tests, which will confirm or disconfirm that everything is
> working properly as far as this module is concerned.
I see -- another, different use for this test. You put "echo value" or
something in the if __name__ = "__main__" to make sure that the function
is declared properly, or the value was indeed created.
Are tests like this native to Python? I mean, I understand that these
names may be unique to Python, but do people use similar techniques to
this in Java and C?
Erik