4 ms·
More often than not you are receiving a list from some function, not constructing it manually. As an example: Say you have a GUI widget that can contain many e
by cool-RR 16y ago
More often than not you are receiving a list from some function, not constructing it manually.
As an example: Say you have a GUI widget that can contain many entries, and you call `widget.get_entries()` which returns a list with all the entries. But if you know there must be only one entry, you can do `(entry,) = widget.get_entries()`.
- jemfinch 16y agoThen it should make a method which returns its known, sole entry. Returning a list of entries from a widget which will always contain only one entry is the logical equivalent to converting a function return value to a string and then expecting the client to convert it back from a string. That is to say, it's necessary in a general case (e.g., a Widget super class) but should not be exposed that way in some specific cases (e.g., your subclass wherein you know there will always be one entry). In reality, you shouldn't be mucking with the entries of a widget at all; you should tell the widget what to do and it should adjust its entries as necessary). Demeter's law and all.
- j_baker 16y agoI notice a lot of "shoulds" in this comment. Unfortunately, what should be and what is aren't always the same thing.
- jemfinch 16y agoNo doubt! But since we're on the subject of "how to make code like this better" it seems appropriate to discuss what's really wrong with the code, rather than just what sort of duct tape style guidelines we can use to patch over its flaws :)
- xiongchiamiov 16y agoVery often we can't change the API (standard library or such). Should we not change our code to address the issue as best we can?
- swolchok 16y agoThis is Python. Subclass it and fix the problem, unless the guts are so opaque that your code would be littered with subclasses and you can't figure out an elegant, general way of fixing it (unlikely).
- tmsh 16y agoThis is Sparta. class SpartanList(list): def foot(self): return self[0] assert l.foot() return l.foot()