From 18d28f3d0d19cc55ce0dbdbd5419eaece12ea20c Mon Sep 17 00:00:00 2001 From: Ernesto Arbitrio Date: Fri, 2 Feb 2024 14:05:32 +0100 Subject: [PATCH] refactor code for dimension elements pt2 --- src/cr/cube/dimension.py | 25 +++++++++++-------------- src/cr/cube/util.py | 12 ++++++++++++ 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/cr/cube/dimension.py b/src/cr/cube/dimension.py index d4eb614b8..fb1778829 100644 --- a/src/cr/cube/dimension.py +++ b/src/cr/cube/dimension.py @@ -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 @@ -17,6 +17,8 @@ ) from cr.cube.util import lazyproperty +from .util import format, format_datetime + DATETIME_FORMATS = { "Y": "%Y", "Q": "%Y-%m", @@ -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 diff --git a/src/cr/cube/util.py b/src/cr/cube/util.py index 454473d6c..e0e43601e 100644 --- a/src/cr/cube/util.py +++ b/src/cr/cube/util.py @@ -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