overriding file.readline: "an integer is required"

Gary Herron gherron at islandtraining.com
Thu Jul 31 00:10:36 CEST 2008


kj wrote:
> I'm trying to subclass file, overriding the readline method.  The
> new method definition begins with
>
>     def readline(self, size=None):
>         line = self.file.readline(size)
>         # etc., etc.
>
> ...where the self.file attribute is a regular file object.
>
> This works fine if I invoke the new method with an integer argument,
> but if I invoke it without arguments, I get the error
>
> TypeError: an integer is required
>
> ...which I suppose comes from the call to self.file.readline(None).
>
> I know that I could rewrite the method like this:
>
>     def readline(self, size=None):
>         if size == None:
>             line = self.file.readline()
>         else:
>             line = self.file.readline(size)
>         # etc., etc.
>
> ...but this seems to me exceptionally awkward.  (Actually, it's worse
> than awkward: it fails to complain when the overriding method is
> called with the argument None.  It would be better to test for the
> number of arguments passed to the function, but I can't figure out
> how to do this either.)
>
> Is there a better idiom?
>   

Since the manual implies that negative values have no effect, try this:

    def readline(self, size=-1):
        line = self.file.readline(size)
        # etc., etc.

I tested this (just barely), and it seems to work as you wish.

Gary Herron




> TIA!
>
> Kynn
>   




More information about the Python-list mailing list