Skip to content

Commit b49b0c8

Browse files
committed
WIP for making subclassable FrameAttribute w/ convert_input method (broken)
1 parent cdef722 commit b49b0c8

2 files changed

Lines changed: 89 additions & 38 deletions

File tree

‎astropy/coordinates/baseframe.py‎

Lines changed: 81 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,37 @@ def __init__(self, default=None, secondary_attribute=''):
8888
self.default = default
8989
self.secondary_attribute = secondary_attribute
9090

91+
def convert_input(self, value):
92+
"""
93+
Validate the input ``value`` and convert to expected attribute class.
94+
95+
The base method here does nothing, but subclasses can implement this
96+
as needed. The method should catch any internal exceptions and raise
97+
ValueError with an informative message.
98+
99+
The method returns the validated input along with a boolean that indicates
100+
whether the input value was actually converted. If the input value was
101+
already the correct type then the ``converted`` return value should be
102+
``False``.
103+
104+
Parameters
105+
----------
106+
value : object
107+
Input value to be converted.
108+
109+
Returns
110+
-------
111+
out, converted : correctly-typed object, boolean
112+
Tuple consisting of the correctly-typed object and a boolean which
113+
indicates if conversion was actually performed.
114+
115+
Raises
116+
------
117+
ValueError
118+
If the input is not valid for this attribute.
119+
"""
120+
return value, False
121+
91122
def __get__(self, instance, cls=None):
92123
# Find thyself in host class or any parents
93124
if not hasattr(self, 'name'):
@@ -113,12 +144,61 @@ def __get__(self, instance, cls=None):
113144
if out is None:
114145
out = self.default
115146

147+
out, converted = self.convert_input(out)
148+
if converted:
149+
setattr('_' + self.name, out)
150+
116151
return out
117152

118153
def __set__(self, instance, val):
119154
raise AttributeError('Cannot set frame attribute')
120155

121156

157+
class TimeFrameAttribute(FrameAttribute):
158+
"""
159+
Frame attribute descriptor for quantities that are Time objects.
160+
"""
161+
def convert_input(self, value):
162+
"""
163+
Convert input value to a Time object and validate by running through the
164+
Time constructor. Also check that the input was a scalar.
165+
166+
Parameters
167+
----------
168+
value : object
169+
Input value to be converted.
170+
171+
Returns
172+
-------
173+
out, converted : correctly-typed object, boolean
174+
Tuple consisting of the correctly-typed object and a boolean which
175+
indicates if conversion was actually performed.
176+
177+
Raises
178+
------
179+
ValueError
180+
If the input is not valid for this attribute.
181+
"""
182+
from ..time import Time
183+
184+
if isinstance(value, Time):
185+
out = value
186+
converted = False
187+
else:
188+
try:
189+
out = Time(value)
190+
except Exception as err:
191+
raise ValueError('Invalid time input {0}={1!r}\n{2}'
192+
.format(self.name, value, err))
193+
converted = True
194+
195+
if not out.isscalar:
196+
raise ValueError('Time input {0}={1!r} must be a single (scalar) value'
197+
.format(self.name, value))
198+
199+
return out, converted
200+
201+
122202
@six.add_metaclass(FrameMeta)
123203
class BaseCoordinateFrame(object):
124204
"""
@@ -132,12 +212,6 @@ class BaseCoordinateFrame(object):
132212
treated as the default representation of this frame. This is the
133213
representation assumed by default when the frame is created.
134214
135-
* `time_attr_names`
136-
A sequence of attribute names that must be `~astropy.time.Time` objects.
137-
When given as keywords in the initializer, these will be converted if
138-
possible (e.g. from the string 'J2000' to the appropriate
139-
`~astropy.time.Time` object). Defaults to ``('equinox', 'obstime')``.
140-
141215
* `~astropy.coordinates.FrameAttribute` class attributes
142216
Frame attributes such as ``FK4.equinox`` or ``FK4.obstime`` are defined
143217
using a descriptor class. See the narrative documentation or
@@ -149,7 +223,7 @@ def get_frame_attr_names(cls):
149223
out = {}
150224
for mro_cls in cls.__mro__:
151225
for name, val in mro_cls.__dict__.items():
152-
if val.__class__ is FrameAttribute:
226+
if issubclass(val.__class__, FrameAttribute):
153227
out[name] = getattr(mro_cls, name)
154228
return out
155229

@@ -213,8 +287,6 @@ def representation_units(self):
213287

214288
default_representation = None
215289

216-
time_attr_names = ('equinox', 'obstime') # Attributes that must be Time objects
217-
218290
# This __new__ provides for backward-compatibility with pre-0.4 API.
219291
# TODO: remove in 1.0
220292
def __new__(cls, *args, **kwargs):
@@ -285,10 +357,6 @@ def __init__(self, *args, **kwargs):
285357

286358
if fnm in kwargs:
287359
value = kwargs.pop(fnm)
288-
# If attribute is a time (equinox, obstime) then validate and force
289-
# into a Time object by running through the Time constructor
290-
if fnm in self.time_attr_names:
291-
value = _convert_to_time(fnm, value)
292360
setattr(self, '_' + fnm, value)
293361
else:
294362
setattr(self, '_' + fnm, fdefault)
@@ -767,20 +835,3 @@ def __setattr__(self, name, value):
767835
super(GenericFrame, self).__setattr__(name, value)
768836

769837

770-
def _convert_to_time(attr, value):
771-
"""
772-
Convert input value to a Time object and validate by running through the
773-
Time constructor. Also check that the input was a scalar.
774-
"""
775-
from ..time import Time
776-
try:
777-
out = Time(value)
778-
except Exception as err:
779-
raise ValueError('Invalid time input {0}={1!r}\n{2}'
780-
.format(attr, value, err))
781-
782-
if not out.isscalar:
783-
raise ValueError('Time input {0}={1!r} must be a single (scalar) value'
784-
.format(attr, value))
785-
786-
return out

‎astropy/coordinates/builtin_frames.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from .representation import (SphericalRepresentation, CartesianRepresentation,
2222
UnitSphericalRepresentation)
2323
from .baseframe import (BaseCoordinateFrame, frame_transform_graph, GenericFrame,
24-
FrameAttribute)
24+
FrameAttribute, TimeFrameAttribute)
2525
from .transformations import FunctionTransform, DynamicMatrixTransform
2626

2727

@@ -103,7 +103,7 @@ class FK5(BaseCoordinateFrame):
103103
"""
104104

105105
default_representation = SphericalRepresentation
106-
equinox = FrameAttribute(default=_EQUINOX_J2000)
106+
equinox = TimeFrameAttribute(default=_EQUINOX_J2000)
107107

108108
@staticmethod
109109
def _precession_matrix(oldequinox, newequinox):
@@ -159,8 +159,8 @@ class FK4(BaseCoordinateFrame):
159159
"""
160160

161161
default_representation = SphericalRepresentation
162-
equinox = FrameAttribute(default=_EQUINOX_B1950)
163-
obstime = FrameAttribute(default=None, secondary_attribute='equinox')
162+
equinox = TimeFrameAttribute(default=_EQUINOX_B1950)
163+
obstime = TimeFrameAttribute(default=None, secondary_attribute='equinox')
164164

165165

166166
@frame_transform_graph.transform(FunctionTransform, FK4, FK4)
@@ -196,8 +196,8 @@ class FK4NoETerms(BaseCoordinateFrame):
196196
"""
197197

198198
default_representation = SphericalRepresentation
199-
equinox = FrameAttribute(default=_EQUINOX_B1950)
200-
obstime = FrameAttribute(default=None, secondary_attribute='equinox')
199+
equinox = TimeFrameAttribute(default=_EQUINOX_B1950)
200+
obstime = TimeFrameAttribute(default=None, secondary_attribute='equinox')
201201

202202
@staticmethod
203203
def _precession_matrix(oldequinox, newequinox):
@@ -301,9 +301,9 @@ class AltAz(BaseCoordinateFrame):
301301
'unitspherical': {'names': ('az', 'alt'), 'units': (u.deg, u.deg)}
302302
}
303303
default_representation = SphericalRepresentation
304-
equinox = FrameAttribute(default=_EQUINOX_B1950)
304+
equinox = TimeFrameAttribute(default=_EQUINOX_B1950)
305305
location = FrameAttribute(default=None)
306-
obstime = FrameAttribute(default=None)
306+
obstime = TimeFrameAttribute(default=None)
307307

308308
def __init__(self, *args, **kwargs):
309309
from warnings import warn

0 commit comments

Comments
 (0)