Skip to content

Commit

Permalink
refactor code for dimension elements pt2
Browse files Browse the repository at this point in the history
  • Loading branch information
ernestoarbitrio committed Feb 2, 2024
1 parent 2b6a61b commit 18d28f3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
25 changes: 11 additions & 14 deletions src/cr/cube/dimension.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

import copy
from collections.abc import Sequence
from datetime import datetime
from typing import Dict, List, Optional, Tuple, Union, Callable
from functools import partial
from typing import Callable, Dict, List, Optional, Tuple, Union

import numpy as np

Expand All @@ -17,6 +17,8 @@
)
from cr.cube.util import lazyproperty

from .util import format, format_datetime

DATETIME_FORMATS = {
"Y": "%Y",
"Q": "%Y-%m",
Expand All @@ -32,24 +34,19 @@
}


def _formatter(dimension_type, typedef, out_format) -> Callable:
def _formatter(dimension_type, typedef, out_format) -> Union[Callable, partial]:
"""Returns a formatting function according to the dimension type."""

def format(x) -> str:
return str(x)

def format_datetime(x) -> str:
try:
return datetime.strptime(x, orig_format).strftime(out_format)
except ValueError:
return str(x)

if dimension_type != DT.DATETIME:
formatter = format
formatter: Union[Callable, partial] = format
else:
resolution = typedef["subtype"].get("resolution")
orig_format: str = DATETIME_FORMATS.get(resolution) or ""
formatter = format_datetime if orig_format and out_format else format
formatter = (
partial(format_datetime, orig_format=orig_format, out_format=out_format)
if orig_format and out_format
else format
)
return formatter


Expand Down
12 changes: 12 additions & 0 deletions src/cr/cube/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,21 @@

"""Utility functions for crunch cube, as well as other modules."""

from datetime import datetime
import functools


def format(x) -> str:
return str(x)


def format_datetime(x, orig_format, out_format) -> str:
try:
return datetime.strptime(x, orig_format).strftime(out_format)
except ValueError:
return str(x)


class lazyproperty:
"""Decorator like @property, but evaluated only on first access.
Like @property, this can only be used to decorate methods having only
Expand Down

0 comments on commit 18d28f3

Please sign in to comment.