Skip to content

Instantly share code, notes, and snippets.

@codeinthehole
Created June 21, 2017 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeinthehole/112fce2d4a688b3aa7039d5f9bbe0464 to your computer and use it in GitHub Desktop.
Save codeinthehole/112fce2d4a688b3aa7039d5f9bbe0464 to your computer and use it in GitHub Desktop.
Example value objects using Python 3.6's typing.NamedTuple functionality
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