2 ms·
When 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 = name
by sevensor 9y ago
When 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.)