3 ms·
Setting default values for the namedtuple requires subclassing it, though, which is its own little bag of fun. See all the wailing and gnashing of teeth on SO:
by mikepurvis 9y ago
Setting default values for the namedtuple requires subclassing it, though, which is its own little bag of fun. See all the wailing and gnashing of teeth on SO: https://stackoverflow.com/search?q=namedtuple+subclass https://stackoverflow.com/search?q=namedtuple+subclass
- sevensor 9y agoWhen this is an issue, I tend to create a namedtuple with default values for the fields at the same time I'm defining the namedtuple type itself. NT = namedtuple("NT", ('a', 'b')) default_NT = NT(42, 'foo') And then later, if I want to initialize only one field: my_new_NT = default_NT._replace(a=7)
- mikepurvis 9y agoI guess that works, but it's a pretty big departure from the expected API of a normal namedtuple, or any other object-with-constructor, for that matter.
- sevensor 9y agoIf you really want it to look more traditional, you could do: NT.new = lambda **kwargs: NT(42, 'foo')._replace(**kwargs) Now you can make NT objects like so: nt1 = NT.new() nt2 = NT.new(b='bar') You can call it something else if calling it "new" makes you feel weird. (I'd call it something else, but naming things is hard.)
- JelleZijlstra 9y agoIf you're using Python 3.6, it's a lot easier now. You can do: from typing import NamedTuple class Point(NamedTuple): x: float y: float = 0.0 and then Point(1.0).y == 0.0.
- sevensor 9y agoThat's quite nice!