GWSL-Source icon indicating copy to clipboard operation
GWSL-Source copied to clipboard

refactoring code with truth value test

Open idiomaticrefactoring opened this issue 3 years ago • 4 comments
trafficstars

refactoring code with truth value test which is more pythonic, concise, readable and efficient; how do think this change which has practical value?

idiomaticrefactoring avatar Feb 13 '22 12:02 idiomaticrefactoring

refactoring code with truth value test which is more pythonic, concise, readable and efficient; how do think this change which has practical value?

How practical do you think it would be?

Pololot64 avatar Feb 14 '22 04:02 Pololot64

Thanks for your comments. Because we find that many developers want to make their code more pythonic. And we find that many books (e.g., writing idiomatic Python) also give some guidance to help them improve their code more pythonic. For example, using truth value test, it is more concise , efficient and pythonic. Specifically,

code='''
option={}
if option!={}:
    pass
'''
code2='''
option={}
if not option:
    pass
'''

import timeit
print(timeit.timeit(code,number=1000000))
print(timeit.timeit(code2,number=1000000))
Output:
0.029162790999999966
0.018889624999999965

Although it is a small code fragment, we could see that the running efficiency also is improved.

idiomaticrefactoring avatar Feb 17 '22 02:02 idiomaticrefactoring

Do you realize that your code does the opposite of the original?

Pololot64 avatar Feb 17 '22 14:02 Pololot64

Thanks for your reminder.

idiomaticrefactoring avatar Feb 18 '22 02:02 idiomaticrefactoring