6 ms·
I agree with everything in the article, but I would like to add one observation: The article uses as an example of two arguments, a byte string and a string sp
by teddyh 5y ago
I agree with everything in the article, but I would like to add one observation:
The article uses as an example of two arguments, a byte string and a string specifying the character encoding of the first argument. Having two arguments so strongly associated with each other as separate arguments is a slight code smell. One should contemplate unifying them into a compound type (like a class instance) which includes both arguments. It’s not always reasonable, of course, and may add more complexity than it saves. But one should keep an eye out for this.
- blip54321 5y agoThat tends to turn Python into Java....
- teddyh 5y agoYes, you should not do it in case it doesn’t help. But it sometimes does help.
- smitty1e 5y agoA class seems heavy. The tuple() is a great way to keep it light.
- teddyh 5y agoUse a named tuple. This way, you can turn it into a class if it ever becomes necessary without changing any other code.
- SethMLarson 5y agoI'd recommend dataclasses over namedtuples. In almost every case the "iterability" of a namedtuple ends up not being necessary (and can be a footgun!) what you really want is a lightweight namespace with types i.e. dataclasses!
- wheelerof4te 5y agoYes, but only for compound types with 3-4 values, maximum. If you need something to store 7-8 different value types, either make a class or reach for named tuple. I tried using regular tuples as lightweight objects, it does not work.
- mattarm 5y agoAgreed, especially if the related values occur a lot in a program and are thought of as "thing". E.g. a Point or Line class. I do think this moves the problem of possible argument confusion to the construction of the new type. At some point the association must be expressed in code, and if the association is between two things of the same type the type system can't flag mistakes as errors. A simple data class still helps, even if it doesn't eliminate the problem, because people can more easily remember one Point(x, y) constructor than where "x" and "y" appear in dozens of different functions.
- SethMLarson 5y agoFor more complicated cases I would agree, having a class that encapsulates logic that's inter-dependent is good. However I'd caution against reaching for the class approach for scenarios that can be captured by a function call. Python programmers love functions ;)