Elementary string-parsing

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Tue Feb 5 02:58:27 EST 2008


On Tue, 05 Feb 2008 06:19:12 +0000, Odysseus wrote:

> In article <60osssF1ro06iU5 at mid.uni-berlin.de>,
>  Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote:
> 
>> Another issue is testing.  If you rely on global names it's harder to test
>> individual functions. [...]
>> 
>> In programs without such global names you see quite clearly in the
>> ``def`` line what the function expects as input.
> 
> Good points, although thorough commenting can go a long way to help on 
> both counts. In theory, at least ...

Won't work in practice so well.  Say we have function `f()` and
document that it expects global name `a` to be set to something before
calling it. `f()` is used by other functions so we have to document `a` in
all other functions too.  If we change `f()` to rely on global name `b`
too we have to hunt down every function that calls `f()` and add the
documentation for `b` there too.  It's much work and error prone.  Easy to
get inconsistent or missing documentation this way.

To write or check documentation for a function you have to scan the whole
function body for data in global names and calls to other functions and
repeat the search there.  If you don't let functions communicate via global
names you just have to look at the argument list to see the input sources.

>> def main():
>>     # Main program comes here.
>> 
>> if __name__ == '__main__':
>>     main()
>> 
>> Then main is called when the script is called as program, but not called if
>> you just import the script as module.  For example to test functions or to
>> reuse the code from other scripts.
> 
> I'm using "if __name__ == 'main'" now, but only for test inputs (which 
> will eventually be read from a config file or passed by the calling 
> script -- or something). I hadn't thought of putting code that actually 
> does something there. As for writing modules, that's way beyond where I 
> want to go at this point: I don't know any C and am not sure I would 
> want to ...

What does this have to do with C!?  There's no specific C knowledge
involved here.

>> >>         assert name.startswith('Name: ')
> 
>> It checks if `name` really starts with 'Name: '.  This way I turned the
>> comment into code that checks the assertion in the comment.
> 
> Good idea to check, although this is actually only one of many 
> assumptions I make about the data -- but what happens if the assertion 
> fails? The program stops and the interpreter reports an AssertionError 
> on line whatever?

Yes, you get an `AssertionError`:

In [314]: assert True

In [315]: assert False
---------------------------------------------------------------------------
<type 'exceptions.AssertionError'>        Traceback (most recent call last)

/home/bj/<ipython console> in <module>()

<type 'exceptions.AssertionError'>:

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list