简体   繁体   中英

Python usage of built in all function on list in return statement

I have a method, which needs to return the result of multiple checks for equality. It is an implementation of the __eq__ method of a class, which represents vocables in my application. Here is the code for the return statement:

return all((
    self.first_language_translations == other.first_language_translations,
    self.first_language_phonetic_scripts == other.first_language_phonetic_scripts,
    self.second_language_translations == other.second_language_translations,
    self.second_language_phonetic_scripts == other.second_language_phonetic_scripts
))

I've tested the runtime of this way of doing it and the other way, using and operators. The and operators are slightly faster, maybe 0.05s. It seems logical, because of having to create a list of those boolean values first and then running a function, which might do more than what the corresponding and operators would have done. However, this is probably going to be executed a lot during my applications runtime.

Now I am wondering, if the usage of all in such a case is a good or a bad practice and if it is worth the slowdown, if it is a good practice. My application is all about vocables and might often need to check, whether a vocable or an identical one is already in a list of vocables. It doesn't need to be super fast and I am thinking this might be micro-optimization, so I'd like to use the best practice for such a situation.

Is this a good usage of the built in all function?

No, that's not a good use of all() , since you have a small, fixed number of comparisons to make, and all() isn't even letting you represent it any more succinctly than you would when using and . Using and is more readable, and you should always put readability first unless you've profiled and performance is actually an issue. That said, using and is indeed a tiny bit faster in the worst case, and even faster on average because it'll short circuit on the first False rather than executing all the comparisons every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM