0

Code readability
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Code readability

by Kangus on Sun Apr 04, 2021 11:58 am

While working through 'Contribute to CircuitPython with Git and GitHub' I came across some code in the review section:
Code: Select all | TOGGLE FULL SIZE
def blink_rate(self,rate):
    if not 0 <= rate <= 3:
        raise ValueError('Blink rate must be an integer in the range: 0-3')
     rate = rate & 0x03
     self.blink_rate = rate


It took me a few seconds to figure out why the original code was ask to be changed and the solution.
My first thought was:
Code: Select all | TOGGLE FULL SIZE
def blink_rate(self,rate):
    if rate not in range(4):
        raise ValueError('Blink rate must be an integer in the range: 0-3')
     rate = rate & 0x03


If the object of python is ease of use and readability the 'in range' method is way easier to read.
Next I tried inline assembly with 5 instructions... Circuitpython doesn't do inline assembly, didn't know that..

Kangus
 
Posts: 38
Joined: Sat May 19, 2018 10:01 pm

Re: Code readability

by danhalbert on Sun Apr 04, 2021 1:08 pm

`range()` is a generator that generates successive values, and `in` looks for a value in an arbitrary sequence of values.

So for instance if you did:
Code: Select all | TOGGLE FULL SIZE
if 1001 in range(500):

Python would test 1001 against 0, 1, 2, 3, ..., 499. The <= test, on the other hand, only makes at most two comparisons. The notation is the same as standard math notation: x <= a <= b.

danhalbert
 
Posts: 2430
Joined: Tue Aug 08, 2017 12:37 pm

Re: Code readability

by Kangus on Sun Apr 04, 2021 7:45 pm

My 'concept' of a range test and how pythons range works are not even close.

Code: Select all | TOGGLE FULL SIZE
def blink_rate():
    rate = 2
    if not 0 <= rate <= 3:
        raise ValueError('Blink rate must be an integer in the range: 0-3')
        rate = rate & 0x03
        self.blink_rate = rate
     
if __name__ == '__main__':
    import timeit
    print(timeit.timeit("blink_rate()", setup="from __main__ import blink_rate"))


(test-env) C:\Users\Kevin\test-env>python ttest.py
0.0807116


Code: Select all | TOGGLE FULL SIZE
def blink_rate():
    rate = 2
    if rate not in range(4):
        raise ValueError('Blink rate must be an integer in the range: 0-3')
    rate = rate & 0x03
     
if __name__ == '__main__':
    import timeit
    print(timeit.timeit("blink_rate()", setup="from __main__ import blink_rate"))


(test-env) C:\Users\Kevin\test-env>python ttest2.py
0.2249187

Kangus
 
Posts: 38
Joined: Sat May 19, 2018 10:01 pm

Please be positive and constructive with your questions and comments.