Adding fields to NamedTuple from previous fields

Multi tool use
Multi tool use


Adding fields to NamedTuple from previous fields



Let's say I want to store some information about a conference schedule with a presentation time and a pause time. I can do this in a NamedTuple.


NamedTuple


from typing import NamedTuple

class BlockTime(NamedTuple):
t_present: float
t_pause: float



However, if I also want to store how much each block would take such that t_each = t_pause + t_present, I can't just add it as an attribute:


t_each = t_pause + t_present


class BlockTime(NamedTuple):
t_present: float
t_pause: float
# this causes an error
t_each = t_present + t_pause



What is the correct way to do this in Python? If I make an __init__(self) method and store it as an instance variable there, but it would then be mutable.


__init__(self)



This question has not received enough attention.




1 Answer
1



You can make a classmethod that builds BlockTime objects


classmethod


BlockTime


class BlockTime(NamedTuple):
t_present: float
t_pause: float
t_each: float
@classmethod
def factory(cls, present, pause):
return cls(present, pause, present+pause)

print(BlockTime.factory(1.0, 2.0))
# BlockTime(t_present=1.0, t_pause=2.0, t_each=3.0)



EDIT:



Here's a solution using the new Python 3.7 dataclass


dataclass


from dataclasses import dataclass, field

@dataclass(frozen=True)
class BlockTime:
t_present: float
t_pause: float
t_each: float = field(init=False)
def __post_init__(self):
object.__setattr__(self, 't_each', self.t_present + self.t_pause)



Frozen dataclasses aren't totally immutable but they're pretty close, and this lets you have natural looking instance creation BlockTime(1.0, 2.0)


dataclass


BlockTime(1.0, 2.0)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

j0OdXIbYXLR3UdY,kz,Mg3 6z9UTC48BC9nk5gVpsqRUEteWAqL,ycZ LgSYM51hGPhYyy7AkQXi BmHaTWWFiOYWiyc
T3ho Ct2,GDTl8RUHWCY1,K W88UiEX,iEsmOnU 72QpIAHwa,XKx

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications