4 ms·
If I understand correctly, I think the problem with your second example is that you should avoid checking for `True` with something like `if isFile` but instead
by silvester23 6y ago
If I understand correctly, I think the problem with your second example is that you should avoid checking for `True` with something like `if isFile` but instead `if isFile is True`. That would solve this specific problem (and is also slightly more efficient because no implicit boolean conversion is performed).
- roywiggins 6y agoYou can do that, but loose checking for truthiness is pretty pythonic. It's weird to put "true" in there if you think you're checking a boolean property. If you know you're not, then you realize you need to call the function and then you can remove the "is".
- tgbugs 6y agoThis one is a bit more subtle. Assume there are two classes on that uses @property and one that does not. class Here: @property def booleanPredicate(self): return random_bool() class There: def anotherBooleanPredicate(self): return random_bool() here = Here() there = There() What happens in the following cases? here.booleanPredicate # as expected here.booleanPredicate() # loud failure here.anotherBooleanPredicate # silently always True here.anotherBooleanPredicate() # as expected So you might think that you should _always_ use @property for boolean predicates, except that there are libraries that use the anotherBooleanPredicate version so you are now at risk for silent always True behavior (creeping sanity destroying evil behavior). To prevent the silent failure you should always start by calling the predicate so that it can fail loudly. Worse if someone does a refactor and misses going from @property form to function form then the silent failure literally cannot be detected by running the program (!).