Re: no sys.argc

Jim Roskind (jar@infoseek.com)
Tue, 28 Jun 1994 17:02:57 -0700

> Date: Tue, 28 Jun 94 15:51 EDT
> From: tibbs@dopey.si.com (Mike Tibbs)
>
> Why does the sys module have "argv" but no "argc"?
>
> I have to do:
> if len(sys.argv) == 1:
> print 'Usage..."
>
> instead of:
>
> if sys.argc == 1:
> print 'Usage...'

I didn't do it, but it makes sense to me, so... here's my answer:

You should really wonder why C/C++ provides argc *and* argv to main!
The answer to this C question is (IMHO) that arrays are not "first
class citizens" in C/C++, and trying to find the length of an array
varies from difficult to impossible. If an array has a null
terminator (as does the argv array in C), then you *can* walk the
length of the array in order to find its length. If the array has no
built in terminator, then there is no way to deduce its length. The
bottom line in C was (probably) that so many people needed to know the
length of this array, that as a convenience, this value was
precalculated (someone with more historical perspective might even
tell me that argv wasn't always null terminated!). Folks that live in
the Fortran based for-loop world probably also *love* using stuff like
argc to limit iteration over arrays, rather dealing with pointers ;-).

Actually though, looking at your code fragment, I could ask why you
would write (in C):

if (1 == argc)

rather than:

if (NULL == argv[1])

I probably wouldn't really have written stuff like your sample code,
but if I did, I "wouldn't need no stinkin' argc around here." ;-)

Getting back to Python:

In general, it is a bad practice to put the same data in two places.
The value of argc is *correctly* bundled in the sys.argv list, in the
form of the len(sys.argv), as lists in Python are first class
citizens. With such an approach, it is impossible to cause the data
to become "inconsistent." If you *wish* to cache its value, you can,
but you are tempting fate, and writing with a higher probability of
error than need be. As an example, I'm sure most C programmers worth
their salt (translation of "salt": written lots of C code, and had to
parse args without using some souped up arg parsing library code) have
had argc go astray (a.k.a., written a bug) in one of their programs
when they used argc to track remaining arg counts :-(.

Summary: In C, they almost-sortof-kindof has a motivation for
providing the "convenience" of an argc value. In Python, with real
arrays carrying their own length, the correct architecture falls out.
(or at least that is how it looks with 20-20 hindsight :-) ).

Jim

Jim Roskind
voice: 408.982.4469
fax: 408.986.1889
jar@infoseek.com