Issue 17921: explicit empty check instead of implicit booleaness (original) (raw)
Issue17921
Created on 2013-05-07 02:18 by lesmana, last changed 2022-04-11 14:57 by admin. This issue is now closed.
Messages (3) | ||
---|---|---|
msg188617 - (view) | Author: lesmana (lesmana) | Date: 2013-05-07 02:18 |
Python should have a builtin method `isempty()` which calls the special method name `__isempty__()` for explicit emptiness check. The special method `__isempty__()` should return `True` if the object is "empty" and `False` if the object is "not empty". Observe emptiness check using implicit booleaness: if not somecollection: foo() Note that this code also handles `None`, `0` and `False` silently. If those are possible values then I have to test explicitly: if somecollection is not None and not somecollection: foo() Also handling the `0` and `False` cases will make the code really really ugly. Usually the `None`, `0` or `False` cases only happen in case of a programming error. But if I do not test for them explicitly then they will be handled silently and the error will occur somewhere else in the code. Compare against explicit emptiness check: if not isempty(somecollection): foo() This code will break immediately if somecollection does not have `__isempty__()`. If `None`, `0` or `False` are possible values they will not be handled silently, instead an error will be reported at `isempty()`. Advantage of explicit emptiness check: * More explicit and fluently readable code * No silent implicit booleaness check when code should do emptiness check * Clearer separation of meaning for the special methods `__len__()` and `__empty__()` Possible use case for explicit emptiness check: a list with memory effect. >>> ml = MemoryEffectList() >>> ml.charge() >>> ml.discharge() >>> isempty(ml) True >>> len(ml) == 0 False | ||
msg188618 - (view) | Author: R. David Murray (r.david.murray) * ![]() |
Date: 2013-05-07 02:23 |
Just use len. | ||
msg188619 - (view) | Author: R. David Murray (r.david.murray) * ![]() |
Date: 2013-05-07 02:26 |
Or, to be more helpful than that short answer: if you think there is something that isempty can do that len can't that makes it worth adding complexity to the language, please discuss it on the python-ideas mailing list first. That's the best place to get feedback for ideas like this. |
History | |||
---|---|---|---|
Date | User | Action | Args |
2022-04-11 14:57:45 | admin | set | github: 62121 |
2013-05-08 15:46:25 | barry | set | nosy: + barry |
2013-05-07 02:26:34 | r.david.murray | set | messages: + |
2013-05-07 02:23:32 | r.david.murray | set | status: open -> closednosy: + r.david.murraymessages: + resolution: rejectedstage: resolved |
2013-05-07 02🔞17 | lesmana | create |