Skip to content

Commit 5884dbe

Browse files
authoredOct 20, 2019
Merge pull request #202 from weka-io/percentage-unit
units: added a Percentage unit, with the appropriate rendering
2 parents 78a5775 + 755ad70 commit 5884dbe

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed
 

‎CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
66

77
## [Unreleased]
88

9+
### Added
10+
- units: Added a Percentage class
11+
12+
913
## [0.3.1] - 2019-07-30
1014

1115
### Added

‎easypy/units.py

+24
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,30 @@
55
from easypy.exceptions import TException
66

77

8+
class Percentage(float):
9+
10+
def __repr__(self):
11+
return "{:.1f}%".format(self * 100)
12+
13+
def __format__(self, spec):
14+
width, precision, name = re.match(r"(?:(\d+))?(?:\.(\d*))?(\w+)?", spec).groups()
15+
precision = int(precision) if precision else 1
16+
if name in ("f", None):
17+
ret = "{:.{precision}f}%".format(self * 100, precision=precision)
18+
elif name == "d":
19+
ret = "{}%".format(round(self * 100))
20+
return "{:>{width}}".format(ret, width=width or "")
21+
22+
def _repr_pretty_(self, p, cycle):
23+
# used by IPython
24+
from easypy.colors import MAGENTA
25+
from easypy.humanize import vertbar
26+
if cycle:
27+
p.text('Percentage(...)')
28+
return
29+
p.text(MAGENTA("{1}:{0!r}".format(self, vertbar(self))))
30+
31+
832
class UnknownDataSizeError(TException):
933
template = 'Could not parse size {}'
1034

0 commit comments

Comments
 (0)