my first class: Args

Peter Kleiweg in.aqua.scribis at nl.invalid
Sat Aug 28 22:49:37 CEST 2004


Thanks for your comments. Especially the thing about using
try/except is very useful. I knew about it, but just didn't
"see" I could use it. Something I have to get used to.

More comments below.

Scott David Daniels wrote:

> >     def __iter__(self):
> >         "iterator set-up"
> ^^ useless docstring -- presume the reader knows python
> >         if self._argc == 0 and sys.stdin.isatty():
> >             self.usage()
> >         if self._argc == 0:
> >             self.infile = '<stdin>'
> >             self._stdin = 1
> >             self._in = sys.stdin
> >         else:
> >             self.infile = self._argv.pop(0)
> >             self._argc -= 1
> >             self._stdin = 0
> >             self._in = open(self.infile, 'r')
> >         return self
> ^^
>           try:
>               self.infile = self._argv.pop(0)
>           except IndexError:
>               if sys.stdin.isatty():
>                   self.usage()  # Doesn't return
>               else:
>                   self.infile = '<stdin>'
>                   self._stdin = True
>                   self._in = sys.stdin
>           else:
>               self._stdin = False
>               self._in = open(self.infile, 'r')
>           return self

This is the only instance I didn't follow your recommendation to
use try/except. It is a binary choice: do we use files given on
the command line or stdin? Neither is more natural than the
other. Also, it splits up lines of code that belong together.

Here is my re-write:

    def __iter__(self):
        "iterator: set-up"
        if self._argv:
            self.infile = self._argv.pop(0)
            self._in = open(self.infile, 'r')
            self._stdin = False
        else:
            if sys.stdin.isatty():
                self.usage()  # Doesn't return
            self.infile = '<stdin>'
            self._in = sys.stdin
            self._stdin = True
        return self

The exceptional case is there be no input, and the simplest test
here seems to be a simple if-statement.

> >         return self.next()
> ^^ Loop rather than recur unless you have a good reason.

Your solution looks much better.


> > if __name__ == '__main__':
>  >     ...
> ^^ also nicer to be able to test from included version:
>
> def demo():
>      ...
>
> if __name__ == '__main__':
>      demo()

That doesn't seem very useful. It depends on command line
arguments. If they are missing, it does a sys.exit(), probably
not what you want unless you run the module stand-alone.


-- 
Peter Kleiweg  L:NL,af,da,de,en,ia,nds,no,sv,(fr,it)  S:NL,de,en,(da,ia)
info: http://www.let.rug.nl/~kleiweg/ls.html




More information about the Python-list mailing list