|
| 1 | +""" |
| 2 | +General class for PyGMT parameters. |
| 3 | +""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +from typing import NamedTuple |
| 8 | + |
| 9 | +from pygmt.helpers import is_nonstr_iter |
| 10 | + |
| 11 | + |
| 12 | +class Alias(NamedTuple): |
| 13 | + """ |
| 14 | + Alias PyGMT long-form parameter to GMT single-letter option flag. |
| 15 | + """ |
| 16 | + |
| 17 | + name: str |
| 18 | + modifier: str |
| 19 | + separator: str | None = None |
| 20 | + |
| 21 | + |
| 22 | +class BaseParams: |
| 23 | + """ |
| 24 | + Base class for PyGMT parameters. |
| 25 | +
|
| 26 | + Examples |
| 27 | + -------- |
| 28 | + >>> import dataclasses |
| 29 | + >>> from pygmt.params.base import BaseParams |
| 30 | + >>> |
| 31 | + >>> @dataclasses.dataclass(repr=False) |
| 32 | + ... class Test(BaseParams): |
| 33 | + ... attr1: Any = None |
| 34 | + ... attr2: Any = None |
| 35 | + ... attr3: Any = None |
| 36 | + ... |
| 37 | + ... __aliases__ = [ |
| 38 | + ... Alias("attr1", ""), |
| 39 | + ... Alias("attr2", "+a"), |
| 40 | + ... Alias("attr3", "+b", "/"), |
| 41 | + ... ] |
| 42 | + >>> var = Test(attr1="val1") |
| 43 | + >>> str(var) |
| 44 | + 'val1' |
| 45 | + >>> repr(var) |
| 46 | + "Test(attr1='val1')" |
| 47 | + """ |
| 48 | + |
| 49 | + def __str__(self): |
| 50 | + """ |
| 51 | + String representation of the object that can be passed to GMT directly. |
| 52 | + """ |
| 53 | + values = [] |
| 54 | + for alias in self.__aliases__: |
| 55 | + value = getattr(self, alias.name) |
| 56 | + if value in (None, False): |
| 57 | + continue |
| 58 | + if value is True: |
| 59 | + value = "" |
| 60 | + elif is_nonstr_iter(value): |
| 61 | + value = alias.separator.join(map(str, value)) |
| 62 | + values.append(f"{alias.modifier}{value}") |
| 63 | + return "".join(values) |
| 64 | + |
| 65 | + def __repr__(self): |
| 66 | + """ |
| 67 | + String representation of the object. |
| 68 | + """ |
| 69 | + string = [] |
| 70 | + for alias in self.__aliases__: |
| 71 | + value = getattr(self, alias.name) |
| 72 | + if value is None or value is False: |
| 73 | + continue |
| 74 | + string.append(f"{alias.name}={value!r}") |
| 75 | + return f"{self.__class__.__name__}({', '.join(string)})" |
0 commit comments