8000 Make it possible to str() a vector Distance · skyfielders/python-skyfield@62cca33 · GitHub
[go: up one dir, main page]

Skip to content

Commit 62cca33

Browse files
Make it possible to str() a vector Distance
Without this tweak, the attempt to print was dying with an error, because a NumPy array does not know what to do with a '.6' format string: Traceback (most recent call last): File "tmp9.py", line 9, in <module> print(mars(tt=2457061.5).position) File "/home/brandon/skyfield/skyfield/units.py", line 50, in __str__ return '{0:.6} AU'.format(self.AU) TypeError: non-empty format string passed to object.__format__ In response I have opened: numpy/numpy#5543
1 parent 60db87c commit 62cca33

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

skyfield/tests/test_units.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Tests of whether units behave."""
22

33
from assay import assert_raises
4+
from numpy import array
45
from skyfield import units
56

67
try:
@@ -10,6 +11,10 @@
1011

1112
# needs_astropy = pytest.mark.skipif(u is None, reason='cannot import AstroPy')
1213

14+
def test_stringifying_vector_distance():
15+
a = array([1.23, 4.56])
16+
assert str(units.Distance(AU=a)) == '[ 1.23 4.56] AU'
17+
1318
def test_iterating_over_raw_measurement():
1419
distance = units.Distance(AU=1.234)
1520
with assert_raises(units.UnpackingError):

skyfield/units.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ def __init__(self, AU=None, km=None, m=None):
3434
elif m is not None:
3535
self.m = _auto_convert(m)
3636
self.AU = m / AU_M
37+
else:
38+
raise ValueError('to construct a Distance provide AU, km, or m')
3739

3840
def __getattr__(self, name):
3941
if name == 'km':
@@ -45,7 +47,8 @@ def __getattr__(self, name):
4547
raise AttributeError('no attribute named %r' % (name,))
4648

4749
def __str__(self):
48-
return '{0:.6} AU'.format(self.AU)
50+
AU = self.AU
51+
return ('{0} AU' if hasattr(AU, 'shape') else '{0:.6} AU').format(AU)
4952

5053
def __repr__(self):
5154
return '<{0} {1}>'.format(type(self).__name__, self)

0 commit comments

Comments
 (0)
0