Created
June 21, 2017 13:55
-
-
Save codeinthehole/112fce2d4a688b3aa7039d5f9bbe0464 to your computer and use it in GitHub Desktop.
Example value objects using Python 3.6's typing.NamedTuple functionality
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import typing | |
import datetime | |
class Period(typing.NamedTuple): | |
""" | |
Value object representing a period in time | |
""" | |
start_dt: datetime.datetime # noqa (as flake8 doesn't support this syntax as of v3.3) | |
end_dt: datetime.datetime # noqa | |
def __repr__(self) -> str: | |
return f"{self.start_dt} - {self.end_dt}" | |
# Queries | |
def start_date(self) -> datetime.date: | |
return self.start_dt.date() | |
def end_date(self) -> datetime.date: | |
return self.end_dt.date() | |
# Factories | |
def partition(self, num_partitions): | |
""" | |
Split period into a number of equally sized smaller periods | |
""" | |
seconds_per_partition = int((self.end_dt - self.start_dt).total_seconds() / num_partitions) | |
new_periods = [] | |
boundary = self.start_dt | |
for n in range(num_partitions): | |
period = self.__class__( | |
start_dt=boundary, | |
end_dt=boundary + datetime.timedelta(seconds=seconds_per_partition)) | |
new_periods.append(period) | |
boundary = period.end_dt | |
return new_periods | |
class ElectricityConsumption(typing.NamedTuple): | |
""" | |
Value object representing electricity consumption over a period | |
""" | |
# The period that these consumption values correspond to | |
period: Period | |
electricity_standard: int = None # noqa | |
electricity_day: int = None # noqa | |
electricity_night: int = None # noqa | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment