Comment 3 for bug 372625

Revision history for this message
Alexander Belchenko (bialix) wrote : Re: [Bug 372625] Re: tobinarray end parameter is inconsistent with standard python range behaviour

sneakypete пишет:
> Understood - and thanks for your quick response. Overall this is a
> fantastic module, and has proved very useful for me.

Thanks :-)

> I only raise this because any deviation from python "norms" is a bug
> waiting to happen (fortunately it caused an exception later in my code,
> so I was able to catch it)

Well, when I wrote that code I was more C-guy than Python-guy, may be it
explains something about something. Although I'm still think the current
behavior has some pros.

> To give a quick example:
> for addr in range(0, EEPROM_SIZE, BLOCK_SIZE):
> eeprom.i2c_write(addr, ih.tobinarray(addr, addr + BLOCK_SIZE - 1))
>
> The "-1" is messy, and shouldn't be required (and looks a lot like
> visual basic!).

Well, your code could be even better this way:

      for addr in range(0, EEPROM_SIZE, BLOCK_SIZE):
          eeprom.i2c_write(addr, ih.tobinarray(start=addr,
                                               size=BLOCK_SIZE))

Adding `size' parameter is much simpler solution.

> Another alternative is to create a wrapper function with "pythonic"
> behaviour and deprecate the old function, so existing code is not broken
> but new code is more intuitive.

You can add such wrapper yourself in your code, simply by subclassing
IntelHex. E.g.:

class IntelHexEx(IntelHex):

    def to_binary_array(self, start=None, end=None, pad=None):
        if end is not None:
            end = end - 1
        self.tobinarray(start, end, pad)

That's all :-)