bool v. int distinctions

Peter Otten __peter__ at web.de
Sun Oct 12 13:20:32 EDT 2003


Lee Harr wrote:

> 
> Hi;
> 
> I am wondering if this is a reasonable thing to do:
> 
> 
> class Pinger:
>     def go(self, repeat=False):
>         if repeat is True:
>             repeat = -1
>         elif repeat is False:
>             repeat = 1
>         self.repeat = repeat
>         self.ping()
> 
>     def ping(self):
>         while self.repeat:
>             print 'ping!'
>             if self.repeat > 0:
>                 self.repeat -= 1
> 
> 
> 
> Won't work with 2.1, clearly, but it seems ok in a
> recent 2.2 or in 2.3.
> 
> I guess my only qualm is that
> 
> p = Pinger()
> p.go(repeat=0)
> 
> may be a bit confusing, since it will not ping at all...
> 
> What do you think?

I think it's a bad idea to mix boolean and integer values. It obfuscates the
logic, and many libraries still use 0 as False and 1 as True.
Also, I would separate repetition from action more clearly:

FOREVER = -1
class Pinger2:
    def repeat(self, count=1):
        assert count >= 0 or count == FOREVER, "count must be >=0 or
FOREVER"
        if count == FOREVER:
            while True:
                self.ping()
        else:
            for i in range(count):
                self.ping()

    def ping(self):
        print 'ping!'

You could even go further and change repeat() into a function that takes an
additional callable oject:

def repeat(self, count, action)

Peter




More information about the Python-list mailing list