4 ms·
Why that underscore? I thought that’s a signal for “method is for internal use, only”. Also (but a bit minor, given that Google tells me Python’s named tuples
by Someone 5y ago
Why that underscore? I thought that’s a signal for “method is for internal use, only”.
Also (but a bit minor, given that Google tells me Python’s named tuples are immutable, so I guess programmers will know that): if I were to read foo._replace(bar=42) I would think that to modify foo.
Because of that, I like scala’s foo.copy(bar=42) more. It makes it clearer that you have to do foo = foo.copy(bar=42) to ‘change’ the value of foo (actually: bind it to a new value).
- rjmorris 5y agoThe underscore is to avoid conflicts with your own attributes named make, asdict, etc. So you could do: MyClass = namedtuple("MyClass", ["make", "asdict", "fields"]) x = MyClass(make=10, asdict=11, fields=12) print(x.asdict) The "underscore-to-avoid-naming-conflicts" approach is used elsewhere in the Python standard library, too, although another example isn't coming to me at the moment.
- nerdponx 5y agoPerhaps even weirder, the Enum class uses names like `_value_`. At one time, inventing nonstandard "magic method" names like `__value__` was considered off-limits, because in principle those names could later be used by the Python language spec itself. In practice, such additions have been very rare, and library authors have become a lot less squeamish about defining their own. The core data model of "almost everything is a mutable lookup table" can be easy to work with and reason about at times, but sometimes it's a little too simple, and you end up with these kinds of ad-hoc and inconsistent workarounds even in the standard library.
- BerislavLopac 5y agoThat is correct, although I agree with the GP that it's a bit unclear. My preferred practice for this is to put the underscore at the end, so it would be make_ and asdict_