Skip to content

Commit

Permalink
remove fget completely
Browse files Browse the repository at this point in the history
Co-authored-by: Marten van Kerkwijk <mhvk@astro.utoronto.ca>
Signed-off-by: Nathaniel Starkman (@nstarman) <nstarkman@protonmail.com>
  • Loading branch information
nstarman and mhvk committed Nov 3, 2021
1 parent bd1be52 commit 0f6f8e9
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 43 deletions.
5 changes: 2 additions & 3 deletions astropy/cosmology/flrw.py
Expand Up @@ -246,9 +246,8 @@ def __init__(self, H0, Om0, Ode0, Tcmb0=0.0*u.K, Neff=3.04, m_nu=0.0*u.eV,
self._Tnu0 = 0.0 * u.K
self._Onu0 = 0.0

# now set m_nu Parameter (Note the value is calculated and not
# influenced by this value)
self.m_nu = m_nu
# now set m_nu Parameter (Note the value is calculated by the validator)
self.m_nu = ...

# -------------------

Expand Down
38 changes: 17 additions & 21 deletions astropy/cosmology/parameter.py
@@ -1,6 +1,7 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst

import astropy.units as u
from astropy.utils.decorators import classproperty

__all__ = ["Parameter"]

Expand All @@ -12,19 +13,16 @@ class Parameter:
Parameters
----------
fget : callable[[type], Any] or None, optional
Function to get the value from instances of the cosmology class.
If None (default) returns the corresponding private attribute.
Often not set here, but as a decorator with ``getter``.
fvalidate : callable[[object, object, Any], Any] or {'default', 'float'}, optional
fvalidate : callable[[object, object, Any], Any] or str, optional
Function to validate the Parameter value from instances of the
cosmology class. If "default", uses default validator to assign units
(with equivalencies), if Parameter has units. If "float" will first do
units, then take the float value.
Often not set here, but through a decorator with ``validator``.
(with equivalencies), if Parameter has units.
For other valid string options,
see :attr:`~astropy.cosmology.Parameter.registered_validators`.
'fvalidate' can also be set through a decorator with
:meth:`~astropy.cosmology.Parameter.validator`.
doc : str or None, optional
Parameter description. If 'doc' is None and 'fget' is not, then 'doc'
is taken from ``fget.__doc__``.
Parameter description.
unit : unit-like or None (optional, keyword-only)
The `~astropy.units.Unit` for the Parameter. If None (default) no
unit as assumed.
Expand All @@ -49,7 +47,7 @@ class Parameter:

_registry_validators = {}

def __init__(self, fget=None, fvalidate="default", doc=None, *,
def __init__(self, fvalidate="default", doc=None, *,
unit=None, equivalencies=[], fmt=".3g", derived=False):
# parse registered fvalidate
if callable(fvalidate):
Expand All @@ -63,9 +61,7 @@ def __init__(self, fget=None, fvalidate="default", doc=None, *,
raise TypeError("`fvalidate` must be a function or "
f"{self._registry_validators.keys()}")

self.__doc__ = fget.__doc__ if (doc is None and fget is not None) else doc
self._fget = fget if not hasattr(fget, "fget") else fget.__get__
# TODO! better detection if `fget` is a descriptor.
self.__doc__ = doc
self._fvalidate = fvalidate

# units stuff
Expand All @@ -75,7 +71,6 @@ def __init__(self, fget=None, fvalidate="default", doc=None, *,
# misc
self._fmt = str(fmt)
self._derived = derived
self.__wrapped__ = fget # so always have access to `fget`

def __set_name__(self, cosmo_cls, name):
# attribute name
Expand Down Expand Up @@ -110,10 +105,6 @@ def derived(self):
# -------------------------------------------
# descriptor and property-like methods

@property
def fget(self):
return self._fget

def __get__(self, cosmology, cosmo_cls=None):
# get from class
if cosmology is None:
Expand Down Expand Up @@ -152,7 +143,7 @@ def validator(self, fvalidate):
`~astropy.cosmology.Parameter`
Copy of this Parameter but with custom ``fvalidate``.
"""
desc = type(self)(fget=self.fget, fvalidate=fvalidate,
desc = type(self)(fvalidate=fvalidate,
doc=self.__doc__, fmt=self.format_spec,
unit=self.unit, equivalencies=self.equivalencies,
derived=self.derived)
Expand Down Expand Up @@ -218,6 +209,11 @@ def register(fvalidate):

return register

@classproperty
def registered_validators(cls):
"""Return keys view of registered validators."""
return cls._registry_validators.keys()

# -------------------------------------------

def __repr__(self):
Expand Down Expand Up @@ -261,5 +257,5 @@ def _validate_non_negative(cosmology, param, value):
"""Parameter value validator where value is a positive float."""
value = _validate_to_float(cosmology, param, value)
if value < 0.0:
raise ValueError(f"{param.name} can not be negative.")
raise ValueError(f"{param.name} cannot be negative.")
return value
6 changes: 3 additions & 3 deletions astropy/cosmology/tests/test_flrw.py
Expand Up @@ -106,7 +106,7 @@ def test_Om0(self, cosmo_cls, cosmo):
# validation
assert cosmo_cls.Om0.validate(cosmo, 1) == 1
assert cosmo_cls.Om0.validate(cosmo, 10 * u.one) == 10
with pytest.raises(ValueError, match="Om0 can not be negative"):
with pytest.raises(ValueError, match="Om0 cannot be negative"):
cosmo_cls.Om0.validate(cosmo, -1)

# on the instance
Expand Down Expand Up @@ -154,7 +154,7 @@ def test_Neff(self, cosmo_cls, cosmo):
# validation
assert cosmo_cls.Neff.validate(cosmo, 1) == 1
assert cosmo_cls.Neff.validate(cosmo, 10 * u.one) == 10
with pytest.raises(ValueError, match="Neff can not be negative"):
with pytest.raises(ValueError, match="Neff cannot be negative"):
cosmo_cls.Neff.validate(cosmo, -1)

# on the instance
Expand Down Expand Up @@ -195,7 +195,7 @@ def test_Ob0(self, cosmo_cls, cosmo):
assert cosmo_cls.Ob0.validate(cosmo, None) is None
assert cosmo_cls.Ob0.validate(cosmo, 0.1) == 0.1
assert cosmo_cls.Ob0.validate(cosmo, 0.1 * u.one) == 0.1
with pytest.raises(ValueError, match="Ob0 can not be negative"):
with pytest.raises(ValueError, match="Ob0 cannot be negative"):
cosmo_cls.Ob0.validate(cosmo, -1)
with pytest.raises(ValueError, match="baryonic density can not be larger"):
cosmo_cls.Ob0.validate(cosmo, cosmo.Om0 + 1)
Expand Down
24 changes: 8 additions & 16 deletions astropy/cosmology/tests/test_parameter.py
Expand Up @@ -65,32 +65,24 @@ def test_Parameter_init(self):
"""Test :class:`astropy.cosmology.Parameter` instantiation."""
# defaults
parameter = Parameter()
assert parameter.fget is None
assert parameter.fvalidate is _validate_with_unit
assert parameter.unit is None
assert parameter.equivalencies == []
assert parameter.format_spec == ".3g"
assert parameter.derived is False
assert parameter.__wrapped__ is parameter.fget

# setting all kwargs
parameter = Parameter(fget=lambda x: x, fvalidate="float", doc="DOCSTRING",
parameter = Parameter(fvalidate="float", doc="DOCSTRING",
unit="km", equivalencies=[u.mass_energy()],
fmt=".4f", derived=True)
assert parameter.fget(2) == 2
assert parameter.fvalidate is _validate_to_float
assert parameter.unit is u.km
assert parameter.equivalencies == [u.mass_energy()]
assert parameter.format_spec == ".4f"
assert parameter.derived is True
assert parameter.__wrapped__ is parameter.fget

def test_Parameter_instance_attributes(self, all_parameter):
"""Test :class:`astropy.cosmology.Parameter` attributes from init."""
# property
assert hasattr(all_parameter, "fget")
assert all_parameter.fget is None or callable(all_parameter.fget)

assert hasattr(all_parameter, "fvalidate")
assert callable(all_parameter.fvalidate)

Expand All @@ -101,17 +93,11 @@ def test_Parameter_instance_attributes(self, all_parameter):
assert hasattr(all_parameter, "_equivalencies")
assert hasattr(all_parameter, "_fmt")
assert hasattr(all_parameter, "_derived")
assert hasattr(all_parameter, "__wrapped__")

# __set_name__
assert hasattr(all_parameter, "_attr_name")
assert hasattr(all_parameter, "_attr_name_private")

def test_Parameter_fget(self, all_parameter):
"""Test :attr:`astropy.cosmology.Parameter.fget`."""
assert hasattr(all_parameter, "fget")
assert callable(all_parameter.fget) or all_parameter.fget is None

def test_Parameter_fvalidate(self, all_parameter):
"""Test :attr:`astropy.cosmology.Parameter.fvalidate`."""
assert hasattr(all_parameter, "fvalidate")
Expand Down Expand Up @@ -318,7 +304,6 @@ def test_Parameter_instance_attributes(self, param):
# custom from set_name
assert param._attr_name == "param"
assert param._attr_name_private == "_param"
assert hasattr(param, "__wrapped__")

def test_Parameter_fvalidate(self, cosmo, param):
"""Test :attr:`astropy.cosmology.Parameter.fvalidate`."""
Expand Down Expand Up @@ -421,6 +406,13 @@ def func(cosmology, param, value):
finally:
param.__class__._registry_validators.pop("newvalidator", None)

def test_Parameter_registered_validators(self, param):
"""
Test :attr:`astropy.cosmology.Parameter.registered_validators`
is just a keys view of the validators registry.
"""
assert param.registered_validators == param._registry_validators.keys()

# ==============================================================

def test_Parameter_doesnt_change_with_generic_class(self):
Expand Down

0 comments on commit 0f6f8e9

Please sign in to comment.