Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: template indicators with jinja #1120

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"scipy>=1.2",
"statsmodels",
"xarray>=0.17",
"Jinja2",
]

dev_requirements = []
Expand Down
7 changes: 6 additions & 1 deletion xclim/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
from inspect import _empty, signature # noqa
from typing import Any, Mapping, Sequence

import numpy as np
import xarray as xr
from boltons.funcutils import wraps
from jinja2 import Environment

from xclim.core.utils import InputKind, PercentileDataArray

Expand All @@ -34,6 +36,8 @@
"pr_per_period": "{unkown}",
}

jinja_env = Environment()


class AttrFormatter(string.Formatter):
"""A formatter for frequently used attribute values.
Expand Down Expand Up @@ -77,7 +81,8 @@ def format(self, format_string: str, /, *args: Any, **kwargs: dict) -> str:
for k, v in DEFAULT_FORMAT_PARAMS.items():
if k not in kwargs:
kwargs.update({k: v})
return super().format(format_string, *args, **kwargs)
kwargs["np"] = np # noqa
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A bit ugly, maybe there is a better way to add numpy in jinja rendering namespace

return jinja_env.from_string(format_string, globals=kwargs).render()

def format_field(self, value, format_spec):
"""Format a value given a formatting spec.
Expand Down
Loading