response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Generates the ``(unit, doc, represents, aliases, prefixes)``
tuple used to format the unit summary docs in `generate_unit_summary`. | def _iter_unit_summary(
namespace: dict[str, object],
) -> Generator[tuple[UnitBase, str, str, str, Literal["Yes", "No"]], None, None]:
"""
Generates the ``(unit, doc, represents, aliases, prefixes)``
tuple used to format the unit summary docs in `generate_unit_summary`.
"""
from . import core
# Get all of the units, and keep track of which ones have SI
# prefixes
units = []
has_prefixes = set()
for key, val in namespace.items():
# Skip non-unit items
if not isinstance(val, core.UnitBase):
continue
# Skip aliases
if key != val.name:
continue
if isinstance(val, core.PrefixUnit):
# This will return the root unit that is scaled by the prefix
# attached to it
has_prefixes.add(val._represents.bases[0].name)
else:
units.append(val)
# Sort alphabetically, case insensitive
units.sort(key=lambda x: x.name.lower())
for unit in units:
doc = _get_first_sentence(unit.__doc__).strip()
represents = ""
if isinstance(unit, core.Unit):
represents = f":math:`{unit._represents.to_string('latex')[1:-1]}`"
aliases = ", ".join(f"``{x}``" for x in unit.aliases)
yield (
unit,
doc,
represents,
aliases,
"Yes" if unit.name in has_prefixes else "No",
) |
Generates a summary of units from a given namespace. This is used
to generate the docstring for the modules that define the actual
units.
Parameters
----------
namespace : dict
A namespace containing units.
Returns
-------
docstring : str
A docstring containing a summary table of the units. | def generate_unit_summary(namespace: dict[str, object]) -> str:
"""
Generates a summary of units from a given namespace. This is used
to generate the docstring for the modules that define the actual
units.
Parameters
----------
namespace : dict
A namespace containing units.
Returns
-------
docstring : str
A docstring containing a summary table of the units.
"""
docstring = io.StringIO()
docstring.write(
"""
.. list-table:: Available Units
:header-rows: 1
:widths: 10 20 20 20 1
* - Unit
- Description
- Represents
- Aliases
- SI Prefixes
"""
)
template = """
* - ``{}``
- {}
- {}
- {}
- {}
"""
for unit_summary in _iter_unit_summary(namespace):
docstring.write(template.format(*unit_summary))
return docstring.getvalue() |
Generates table entries for units in a namespace that are just prefixes
without the base unit. Note that this is intended to be used *after*
`generate_unit_summary` and therefore does not include the table header.
Parameters
----------
namespace : dict
A namespace containing units that are prefixes but do *not* have the
base unit in their namespace.
Returns
-------
docstring : str
A docstring containing a summary table of the units. | def generate_prefixonly_unit_summary(namespace: dict[str, object]) -> str:
"""
Generates table entries for units in a namespace that are just prefixes
without the base unit. Note that this is intended to be used *after*
`generate_unit_summary` and therefore does not include the table header.
Parameters
----------
namespace : dict
A namespace containing units that are prefixes but do *not* have the
base unit in their namespace.
Returns
-------
docstring : str
A docstring containing a summary table of the units.
"""
from . import PrefixUnit
faux_namespace = {}
for unit in namespace.values():
if isinstance(unit, PrefixUnit):
base_unit = unit.represents.bases[0]
faux_namespace[base_unit.name] = base_unit
docstring = io.StringIO()
template = """
* - Prefixes for ``{}``
- {} prefixes
- {}
- {}
- Only
"""
for unit_summary in _iter_unit_summary(faux_namespace):
docstring.write(template.format(*unit_summary))
return docstring.getvalue() |
Fraction very close to x with denominator at most max_denominator.
The fraction has to be such that fraction/x is unity to within 4 ulp.
If such a fraction does not exist, returns the float number.
The algorithm is that of `fractions.Fraction.limit_denominator`, but
sped up by not creating a fraction to start with.
If the input is zero, an integer or `fractions.Fraction`, just return it. | def maybe_simple_fraction(p: Real, max_denominator: int = 100) -> Real:
"""Fraction very close to x with denominator at most max_denominator.
The fraction has to be such that fraction/x is unity to within 4 ulp.
If such a fraction does not exist, returns the float number.
The algorithm is that of `fractions.Fraction.limit_denominator`, but
sped up by not creating a fraction to start with.
If the input is zero, an integer or `fractions.Fraction`, just return it.
"""
if p == 0 or p.__class__ is int or p.__class__ is Fraction:
return p
n, d = float(p).as_integer_ratio()
a = n // d
# Normally, start with 0,1 and 1,0; here we have applied first iteration.
n0, d0 = 1, 0
n1, d1 = a, 1
while d1 <= max_denominator:
if _JUST_BELOW_UNITY <= n1 / (d1 * p) <= _JUST_ABOVE_UNITY:
return Fraction(n1, d1)
n, d = d, n - a * d
a = n // d
n0, n1 = n1, n0 + a * n1
d0, d1 = d1, d0 + a * d1
return p |
Check that a power can be converted to a floating point value.
Parameters
----------
p : numerical
Power to be converted
Raises
------
ValueError
If the power is an array in which not all elements are equal.
Returns
-------
p : numerical
Equals the input unless the input was iterable and all elements
were the same, in which case it returns the first item. | def validate_power(p: FloatLike | ArrayLike[FloatLike]) -> FloatLike:
"""Check that a power can be converted to a floating point value.
Parameters
----------
p : numerical
Power to be converted
Raises
------
ValueError
If the power is an array in which not all elements are equal.
Returns
-------
p : numerical
Equals the input unless the input was iterable and all elements
were the same, in which case it returns the first item.
"""
if p.__class__ is int or p.__class__ is Fraction:
return p
try:
float(p)
except Exception:
p = np.asanyarray(p)
if ((first := p.flat[0]) == p).all():
# All the same, now check it is OK.
float(first)
return first
else:
raise ValueError(
"Quantities and Units may only be raised to a scalar power"
) from None
else:
return p |
Convert the power to a float, an integer, or a Fraction.
If a fractional power can be represented exactly as a floating point
number, convert it to a float, to make the math much faster; otherwise,
retain it as a `fractions.Fraction` object to avoid losing precision.
Conversely, if the value is indistinguishable from a rational number with a
low-numbered denominator, convert to a Fraction object.
If a power can be represented as an integer, use that.
Parameters
----------
p : float, int, Rational, Fraction
Power to be converted. | def sanitize_power(p: Real) -> Real:
"""Convert the power to a float, an integer, or a Fraction.
If a fractional power can be represented exactly as a floating point
number, convert it to a float, to make the math much faster; otherwise,
retain it as a `fractions.Fraction` object to avoid losing precision.
Conversely, if the value is indistinguishable from a rational number with a
low-numbered denominator, convert to a Fraction object.
If a power can be represented as an integer, use that.
Parameters
----------
p : float, int, Rational, Fraction
Power to be converted.
"""
if p.__class__ is int:
return p
denom = getattr(p, "denominator", None)
if denom is None:
# This returns either a (simple) Fraction or the same float.
p = maybe_simple_fraction(p)
# If still a float, nothing more to be done.
if isinstance(p, float):
return p
# Otherwise, check for simplifications.
denom = p.denominator
if denom == 1:
p = p.numerator
elif (denom & (denom - 1)) == 0:
# Above is a bit-twiddling hack to see if denom is a power of two.
# If so, float does not lose precision and will speed things up.
p = float(p)
return p |
If either input is a Fraction, convert the other to a Fraction
(at least if it does not have a ridiculous denominator).
This ensures that any operation involving a Fraction will use
rational arithmetic and preserve precision. | def resolve_fractions(a: Real, b: Real) -> tuple[Real, Real]:
"""
If either input is a Fraction, convert the other to a Fraction
(at least if it does not have a ridiculous denominator).
This ensures that any operation involving a Fraction will use
rational arithmetic and preserve precision.
"""
# We short-circuit on the most common cases of int and float, since
# isinstance(a, Fraction) is very slow for any non-Fraction instances.
a_is_fraction = (
a.__class__ is not int and a.__class__ is not float and isinstance(a, Fraction)
)
b_is_fraction = (
b.__class__ is not int and b.__class__ is not float and isinstance(b, Fraction)
)
if a_is_fraction and not b_is_fraction:
b = maybe_simple_fraction(b)
elif not a_is_fraction and b_is_fraction:
a = maybe_simple_fraction(a)
return a, b |
Groups the powers and bases in the given
`~astropy.units.CompositeUnit` into positive powers and
negative powers for easy display on either side of a solidus.
Parameters
----------
bases : list of `astropy.units.UnitBase` instances
powers : list of int
Returns
-------
positives, negatives : tuple of lists
Each element in each list is tuple of the form (*base*,
*power*). The negatives have the sign of their power reversed
(i.e. the powers are all positive). | def get_grouped_by_powers(bases, powers):
"""
Groups the powers and bases in the given
`~astropy.units.CompositeUnit` into positive powers and
negative powers for easy display on either side of a solidus.
Parameters
----------
bases : list of `astropy.units.UnitBase` instances
powers : list of int
Returns
-------
positives, negatives : tuple of lists
Each element in each list is tuple of the form (*base*,
*power*). The negatives have the sign of their power reversed
(i.e. the powers are all positive).
"""
positive = []
negative = []
for base, power in zip(bases, powers):
if power < 0:
negative.append((base, -power))
elif power > 0:
positive.append((base, power))
else:
raise ValueError("Unit with 0 power")
return positive, negative |
Given a number, split it into its mantissa and base 10 exponent
parts, each as strings. If the exponent is too small, it may be
returned as the empty string.
Parameters
----------
v : float
format_spec : str, optional
Number representation formatting string
Returns
-------
mantissa, exponent : tuple of strings | def split_mantissa_exponent(v, format_spec=".8g"):
"""
Given a number, split it into its mantissa and base 10 exponent
parts, each as strings. If the exponent is too small, it may be
returned as the empty string.
Parameters
----------
v : float
format_spec : str, optional
Number representation formatting string
Returns
-------
mantissa, exponent : tuple of strings
"""
x = format(v, format_spec).split("e")
if len(x) == 2:
ex = x[1].lstrip("0+")
if len(ex) > 0 and ex[0] == "-":
ex = "-" + ex[1:].lstrip("0")
else:
ex = ""
if ex == "" or (x[0] != "1." + "0" * (len(x[0]) - 2)):
m = x[0]
else:
m = ""
return m, ex |
Partially decomposes a unit so it is only composed of units that
are "known" to a given format.
Parameters
----------
unit : `~astropy.units.UnitBase` instance
func : callable
This function will be called to determine if a given unit is
"known". If the unit is not known, this function should raise a
`ValueError`.
Returns
-------
unit : `~astropy.units.UnitBase` instance
A flattened unit. | def decompose_to_known_units(unit, func):
"""
Partially decomposes a unit so it is only composed of units that
are "known" to a given format.
Parameters
----------
unit : `~astropy.units.UnitBase` instance
func : callable
This function will be called to determine if a given unit is
"known". If the unit is not known, this function should raise a
`ValueError`.
Returns
-------
unit : `~astropy.units.UnitBase` instance
A flattened unit.
"""
from astropy.units import core
if isinstance(unit, core.CompositeUnit):
new_unit = core.Unit(unit.scale)
for base, power in zip(unit.bases, unit.powers):
new_unit = new_unit * decompose_to_known_units(base, func) ** power
return new_unit
elif isinstance(unit, core.NamedUnit):
try:
func(unit)
except ValueError:
if isinstance(unit, core.Unit):
return decompose_to_known_units(unit._represents, func)
raise
return unit
else:
raise TypeError(
f"unit argument must be a 'NamedUnit' or 'CompositeUnit', not {type(unit)}"
) |
Converts a value for a power (which may be floating point or a
`fractions.Fraction` object), into a string looking like either
an integer or a fraction, if the power is close to that. | def format_power(power):
"""
Converts a value for a power (which may be floating point or a
`fractions.Fraction` object), into a string looking like either
an integer or a fraction, if the power is close to that.
"""
if not hasattr(power, "denominator"):
power = maybe_simple_fraction(power)
if getattr(power, "denonimator", None) == 1:
power = power.numerator
return str(power) |
A wrapper around `astropy.utils.misc.did_you_mean` that deals with
the display of deprecated units.
Parameters
----------
s : str
The invalid unit string
all_units : dict
A mapping from valid unit names to unit objects.
deprecated_units : sequence
The deprecated unit names
format_decomposed : callable
A function to turn a decomposed version of the unit into a
string. Should return `None` if not possible
Returns
-------
msg : str
A string message with a list of alternatives, or the empty
string. | def did_you_mean_units(s, all_units, deprecated_units, format_decomposed):
"""
A wrapper around `astropy.utils.misc.did_you_mean` that deals with
the display of deprecated units.
Parameters
----------
s : str
The invalid unit string
all_units : dict
A mapping from valid unit names to unit objects.
deprecated_units : sequence
The deprecated unit names
format_decomposed : callable
A function to turn a decomposed version of the unit into a
string. Should return `None` if not possible
Returns
-------
msg : str
A string message with a list of alternatives, or the empty
string.
"""
def fix_deprecated(x):
if x in deprecated_units:
results = [x + " (deprecated)"]
decomposed = _try_decomposed(all_units[x], format_decomposed)
if decomposed is not None:
results.append(decomposed)
return results
return (x,)
return did_you_mean(s, all_units, fix=fix_deprecated) |
Raises a UnitsWarning about a deprecated unit in a given format.
Suggests a decomposed alternative if one is available.
Parameters
----------
s : str
The deprecated unit name.
unit : astropy.units.core.UnitBase
The unit object.
standard_name : str
The name of the format for which the unit is deprecated.
format_decomposed : callable
A function to turn a decomposed version of the unit into a
string. Should return `None` if not possible | def unit_deprecation_warning(s, unit, standard_name, format_decomposed):
"""
Raises a UnitsWarning about a deprecated unit in a given format.
Suggests a decomposed alternative if one is available.
Parameters
----------
s : str
The deprecated unit name.
unit : astropy.units.core.UnitBase
The unit object.
standard_name : str
The name of the format for which the unit is deprecated.
format_decomposed : callable
A function to turn a decomposed version of the unit into a
string. Should return `None` if not possible
"""
from astropy.units.core import UnitsWarning
message = f"The unit '{s}' has been deprecated in the {standard_name} standard."
decomposed = _try_decomposed(unit, format_decomposed)
if decomposed is not None:
message += f" Suggested: {decomposed}."
warnings.warn(message, UnitsWarning) |
Get a formatter by name.
Parameters
----------
format : str or `astropy.units.format.Base` instance or subclass
The name of the format, or the format instance or subclass
itself.
Returns
-------
format : `astropy.units.format.Base` instance
The requested formatter. | def get_format(format=None):
"""
Get a formatter by name.
Parameters
----------
format : str or `astropy.units.format.Base` instance or subclass
The name of the format, or the format instance or subclass
itself.
Returns
-------
format : `astropy.units.format.Base` instance
The requested formatter.
"""
if format is None:
return Generic
if isinstance(format, type) and issubclass(format, Base):
return format
elif not (isinstance(format, str) or format is None):
raise TypeError(
f"Formatter must a subclass or instance of a subclass of {Base!r} "
f"or a string giving the name of the formatter. {_known_formats()}."
)
format_lower = format.lower()
if format_lower in Base.registry:
return Base.registry[format_lower]
raise ValueError(f"Unknown format {format!r}. {_known_formats()}") |
Test whether the items in value can have arbitrary units.
Numbers whose value does not change upon a unit change, i.e.,
zero, infinity, or not-a-number
Parameters
----------
value : number or array
Returns
-------
bool
`True` if each member is either zero or not finite, `False` otherwise | def can_have_arbitrary_unit(value):
"""Test whether the items in value can have arbitrary units.
Numbers whose value does not change upon a unit change, i.e.,
zero, infinity, or not-a-number
Parameters
----------
value : number or array
Returns
-------
bool
`True` if each member is either zero or not finite, `False` otherwise
"""
return np.all(np.logical_or(np.equal(value, 0.0), ~np.isfinite(value))) |
Determine the required converters and the unit of the ufunc result.
Converters are functions required to convert to a ufunc's expected unit,
e.g., radian for np.sin; or to ensure units of two inputs are consistent,
e.g., for np.add. In these examples, the unit of the result would be
dimensionless_unscaled for np.sin, and the same consistent unit for np.add.
Parameters
----------
function : `~numpy.ufunc`
Numpy universal function
method : str
Method with which the function is evaluated, e.g.,
'__call__', 'reduce', etc.
*args : `~astropy.units.Quantity` or ndarray subclass
Input arguments to the function
Raises
------
TypeError : when the specified function cannot be used with Quantities
(e.g., np.logical_or), or when the routine does not know how to handle
the specified function (in which case an issue should be raised on
https://github.com/astropy/astropy).
UnitTypeError : when the conversion to the required (or consistent) units
is not possible. | def converters_and_unit(function, method, *args):
"""Determine the required converters and the unit of the ufunc result.
Converters are functions required to convert to a ufunc's expected unit,
e.g., radian for np.sin; or to ensure units of two inputs are consistent,
e.g., for np.add. In these examples, the unit of the result would be
dimensionless_unscaled for np.sin, and the same consistent unit for np.add.
Parameters
----------
function : `~numpy.ufunc`
Numpy universal function
method : str
Method with which the function is evaluated, e.g.,
'__call__', 'reduce', etc.
*args : `~astropy.units.Quantity` or ndarray subclass
Input arguments to the function
Raises
------
TypeError : when the specified function cannot be used with Quantities
(e.g., np.logical_or), or when the routine does not know how to handle
the specified function (in which case an issue should be raised on
https://github.com/astropy/astropy).
UnitTypeError : when the conversion to the required (or consistent) units
is not possible.
"""
# Check whether we support this ufunc, by getting the helper function
# (defined in helpers) which returns a list of function(s) that convert the
# input(s) to the unit required for the ufunc, as well as the unit the
# result will have (a tuple of units if there are multiple outputs).
ufunc_helper = UFUNC_HELPERS[function]
if method == "__call__" or (method == "outer" and function.nin == 2):
# Find out the units of the arguments passed to the ufunc; usually,
# at least one is a quantity, but for two-argument ufuncs, the second
# could also be a Numpy array, etc. These are given unit=None.
units = [getattr(arg, "unit", None) for arg in args]
# Determine possible conversion functions, and the result unit.
converters, result_unit = ufunc_helper(function, *units)
if any(converter is False for converter in converters):
# for multi-argument ufuncs with a quantity and a non-quantity,
# the quantity normally needs to be dimensionless, *except*
# if the non-quantity can have arbitrary unit, i.e., when it
# is all zero, infinity or NaN. In that case, the non-quantity
# can just have the unit of the quantity
# (this allows, e.g., `q > 0.` independent of unit)
try:
# Don't fold this loop in the test above: this rare case
# should not make the common case slower.
for i, converter in enumerate(converters):
if converter is not False:
continue
if can_have_arbitrary_unit(args[i]):
converters[i] = None
else:
raise UnitConversionError(
f"Can only apply '{function.__name__}' function to "
"dimensionless quantities when other argument is not "
"a quantity (unless the latter is all zero/infinity/nan)."
)
except TypeError:
# _can_have_arbitrary_unit failed: arg could not be compared
# with zero or checked to be finite. Then, ufunc will fail too.
raise TypeError(
"Unsupported operand type(s) for ufunc {}: '{}'".format(
function.__name__,
",".join([arg.__class__.__name__ for arg in args]),
)
)
# In the case of np.power and np.float_power, the unit itself needs to
# be modified by an amount that depends on one of the input values,
# so we need to treat this as a special case.
# TODO: find a better way to deal with this.
if result_unit is False:
if units[0] is None or units[0] == dimensionless_unscaled:
result_unit = dimensionless_unscaled
else:
if units[1] is None:
p = args[1]
else:
p = args[1].to(dimensionless_unscaled).value
try:
result_unit = units[0] ** p
except ValueError as exc:
# Changing the unit does not work for, e.g., array-shaped
# power, but this is OK if we're (scaled) dimensionless.
try:
converters[0] = units[0].get_converter(dimensionless_unscaled)
except UnitConversionError:
raise exc
else:
result_unit = dimensionless_unscaled
else: # methods for which the unit should stay the same
nin = function.nin
unit = getattr(args[0], "unit", None)
if method == "at" and nin <= 2:
if nin == 1:
units = [unit]
else:
units = [unit, getattr(args[2], "unit", None)]
converters, result_unit = ufunc_helper(function, *units)
# ensure there is no 'converter' for indices (2nd argument)
converters.insert(1, None)
elif method in {"reduce", "accumulate", "reduceat"} and nin == 2:
converters, result_unit = ufunc_helper(function, unit, unit)
converters = converters[:1]
if method == "reduceat":
# add 'scale' for indices (2nd argument)
converters += [None]
else:
if method in {"reduce", "accumulate", "reduceat", "outer"} and nin != 2:
raise ValueError(f"{method} only supported for binary functions")
raise TypeError(
f"Unexpected ufunc method {method}. If this should work, please "
"raise an issue on https://github.com/astropy/astropy"
)
# for all but __call__ method, scaling is not allowed
if unit is not None and result_unit is None:
raise TypeError(
f"Cannot use '{method}' method on ufunc {function.__name__} with a "
"Quantity instance as the result is not a Quantity."
)
if converters[0] is not None or (
unit is not None
and unit is not result_unit
and (not result_unit.is_equivalent(unit) or result_unit.to(unit) != 1.0)
):
# NOTE: this cannot be the more logical UnitTypeError, since
# then things like np.cumprod will not longer fail (they check
# for TypeError).
raise UnitsError(
f"Cannot use '{method}' method on ufunc {function.__name__} with a "
"Quantity instance as it would change the unit."
)
return converters, result_unit |
Check that function output can be stored in the output array given.
Parameters
----------
output : array or `~astropy.units.Quantity` or tuple
Array that should hold the function output (or tuple of such arrays).
unit : `~astropy.units.Unit` or None, or tuple
Unit that the output will have, or `None` for pure numbers (should be
tuple of same if output is a tuple of outputs).
inputs : tuple
Any input arguments. These should be castable to the output.
function : callable
The function that will be producing the output. If given, used to
give a more informative error message.
Returns
-------
arrays : ndarray view or tuple thereof
The view(s) is of ``output``.
Raises
------
UnitTypeError : If ``unit`` is inconsistent with the class of ``output``
TypeError : If the ``inputs`` cannot be cast safely to ``output``. | def check_output(output, unit, inputs, function=None):
"""Check that function output can be stored in the output array given.
Parameters
----------
output : array or `~astropy.units.Quantity` or tuple
Array that should hold the function output (or tuple of such arrays).
unit : `~astropy.units.Unit` or None, or tuple
Unit that the output will have, or `None` for pure numbers (should be
tuple of same if output is a tuple of outputs).
inputs : tuple
Any input arguments. These should be castable to the output.
function : callable
The function that will be producing the output. If given, used to
give a more informative error message.
Returns
-------
arrays : ndarray view or tuple thereof
The view(s) is of ``output``.
Raises
------
UnitTypeError : If ``unit`` is inconsistent with the class of ``output``
TypeError : If the ``inputs`` cannot be cast safely to ``output``.
"""
if isinstance(output, tuple):
return tuple(
check_output(output_, unit_, inputs, function)
for output_, unit_ in zip(output, unit)
)
# ``None`` indicates no actual array is needed. This can happen, e.g.,
# with np.modf(a, out=(None, b)).
if output is None:
return None
if hasattr(output, "__quantity_subclass__"):
# Check that we're not trying to store a plain Numpy array or a
# Quantity with an inconsistent unit (e.g., not angular for Angle).
if unit is None:
raise TypeError(
"Cannot store non-quantity output{} in {} instance".format(
(
f" from {function.__name__} function"
if function is not None
else ""
),
type(output),
)
)
q_cls, subok = output.__quantity_subclass__(unit)
if not (subok or q_cls is type(output)):
raise UnitTypeError(
"Cannot store output with unit '{}'{} "
"in {} instance. Use {} instance instead.".format(
unit,
(
f" from {function.__name__} function"
if function is not None
else ""
),
type(output),
q_cls,
)
)
# check we can handle the dtype (e.g., that we are not int
# when float is required). Note that we only do this for Quantity
# output; for array output, we defer to numpy's default handling.
# Also, any structured dtype are ignored (likely erfa ufuncs).
# TODO: make more logical; is this necessary at all?
if inputs and not output.dtype.names:
result_type = np.result_type(*inputs)
if not (
result_type.names
or np.can_cast(result_type, output.dtype, casting="same_kind")
):
raise TypeError(
"Arguments cannot be cast safely to inplace "
f"output with dtype={output.dtype}"
)
# Turn into ndarray, so we do not loop into array_wrap/array_ufunc
# if the output is used to store results of a function.
return output.view(np.ndarray)
else:
# output is not a Quantity, so cannot obtain a unit.
if not (unit is None or unit is dimensionless_unscaled):
raise UnitTypeError(
"Cannot store quantity with dimension "
"{}in a non-Quantity instance.".format(
f"resulting from {function.__name__} function "
if function is not None
else ""
)
)
return output |
Convert argument to a Quantity (or raise NotImplementedError). | def _as_quantity(a):
"""Convert argument to a Quantity (or raise NotImplementedError)."""
from astropy.units import Quantity
try:
return Quantity(a, copy=COPY_IF_NEEDED, subok=True)
except Exception:
# If we cannot convert to Quantity, we should just bail.
raise NotImplementedError |
Convert arguments to Quantity (or raise NotImplentedError). | def _as_quantities(*args):
"""Convert arguments to Quantity (or raise NotImplentedError)."""
from astropy.units import Quantity
try:
# Note: this should keep the dtype the same
return tuple(Quantity(a, copy=COPY_IF_NEEDED, subok=True, dtype=None) for a in args)
except Exception:
# If we cannot convert to Quantity, we should just bail.
raise NotImplementedError |
Convert to arrays in units of the first argument that has a unit.
If unit_from_first, take the unit of the first argument regardless
whether it actually defined a unit (e.g., dimensionless for arrays). | def _quantities2arrays(*args, unit_from_first=False):
"""Convert to arrays in units of the first argument that has a unit.
If unit_from_first, take the unit of the first argument regardless
whether it actually defined a unit (e.g., dimensionless for arrays).
"""
# Turn first argument into a quantity.
q = _as_quantity(args[0])
if len(args) == 1:
return (q.value,), q.unit
# If we care about the unit being explicit, then check whether this
# argument actually had a unit, or was likely inferred.
if not unit_from_first and (
q.unit is q._default_unit and not hasattr(args[0], "unit")
):
# Here, the argument could still be things like [10*u.one, 11.*u.one]),
# i.e., properly dimensionless. So, we only override with anything
# that has a unit not equivalent to dimensionless (fine to ignore other
# dimensionless units pass, even if explicitly given).
for arg in args[1:]:
trial = _as_quantity(arg)
if not trial.unit.is_equivalent(q.unit):
# Use any explicit unit not equivalent to dimensionless.
q = trial
break
# We use the private _to_own_unit method here instead of just
# converting everything to quantity and then do .to_value(qs0.unit)
# as we want to allow arbitrary unit for 0, inf, and nan.
try:
arrays = tuple((q._to_own_unit(arg)) for arg in args)
except TypeError:
raise NotImplementedError
return arrays, q.unit |
Convert arguments to Quantity, and treat possible 'out'. | def _iterable_helper(*args, out=None, **kwargs):
"""Convert arguments to Quantity, and treat possible 'out'."""
from astropy.units import Quantity
if out is not None:
if isinstance(out, Quantity):
kwargs["out"] = out.view(np.ndarray)
else:
# TODO: for an ndarray output, we could in principle
# try converting all Quantity to dimensionless.
raise NotImplementedError
arrays, unit = _quantities2arrays(*args)
return arrays, kwargs, unit, out |
Convert a structured quantity to an unstructured one.
This only works if all the units are compatible. | def structured_to_unstructured(arr, *args, **kwargs):
"""
Convert a structured quantity to an unstructured one.
This only works if all the units are compatible.
"""
from astropy.units import StructuredUnit
target_unit = arr.unit.values()[0]
def replace_unit(x):
if isinstance(x, StructuredUnit):
return x._recursively_apply(replace_unit)
else:
return target_unit
to_unit = arr.unit._recursively_apply(replace_unit)
return (arr.to_value(to_unit),) + args, kwargs, target_unit, None |
Build structured unit from dtype.
Parameters
----------
dtype : `numpy.dtype`
unit : `astropy.units.Unit`
Returns
-------
`astropy.units.Unit` or tuple | def _build_structured_unit(dtype, unit):
"""Build structured unit from dtype.
Parameters
----------
dtype : `numpy.dtype`
unit : `astropy.units.Unit`
Returns
-------
`astropy.units.Unit` or tuple
"""
if dtype.fields is None:
return unit
return tuple(_build_structured_unit(v[0], unit) for v in dtype.fields.values()) |
Returns an iterator of collapsing any nested unit structure.
Parameters
----------
iterable : Iterable[StructuredUnit | Unit] or StructuredUnit
A structured unit or iterable thereof.
Yields
------
unit | def _izip_units_flat(iterable):
"""Returns an iterator of collapsing any nested unit structure.
Parameters
----------
iterable : Iterable[StructuredUnit | Unit] or StructuredUnit
A structured unit or iterable thereof.
Yields
------
unit
"""
from astropy.units import StructuredUnit
# Make Structured unit (pass-through if it is already).
units = StructuredUnit(iterable)
# Yield from structured unit.
for v in units.values():
if isinstance(v, StructuredUnit):
yield from _izip_units_flat(v)
else:
yield v |
Merge structured Quantities field by field.
Like :func:`numpy.lib.recfunctions.merge_arrays`. Note that ``usemask`` and
``asrecarray`` are not supported at this time and will raise a ValueError if
not `False`. | def merge_arrays(
seqarrays,
fill_value=-1,
flatten=False,
usemask=False,
asrecarray=False,
):
"""Merge structured Quantities field by field.
Like :func:`numpy.lib.recfunctions.merge_arrays`. Note that ``usemask`` and
``asrecarray`` are not supported at this time and will raise a ValueError if
not `False`.
"""
from astropy.units import Quantity, StructuredUnit
if asrecarray:
# TODO? implement if Quantity ever supports rec.array
raise ValueError("asrecarray=True is not supported.")
if usemask:
# TODO: use MaskedQuantity for this case
raise ValueError("usemask=True is not supported.")
# Do we have a single Quantity as input?
if isinstance(seqarrays, Quantity):
seqarrays = (seqarrays,)
# Note: this also converts ndarray -> Quantity[dimensionless]
seqarrays = _as_quantities(*seqarrays)
arrays = tuple(q.value for q in seqarrays)
units = tuple(q.unit for q in seqarrays)
if flatten:
unit = StructuredUnit(tuple(_izip_units_flat(units)))
elif len(arrays) == 1:
unit = StructuredUnit(units[0])
else:
unit = StructuredUnit(units)
return (
(arrays,),
dict(
fill_value=fill_value,
flatten=flatten,
usemask=usemask,
asrecarray=asrecarray,
),
unit,
None,
) |
Like Unit.get_converter, except returns None if no scaling is needed,
i.e., if the inferred scale is unity. | def get_converter(from_unit, to_unit):
"""Like Unit.get_converter, except returns None if no scaling is needed,
i.e., if the inferred scale is unity.
"""
converter = from_unit.get_converter(to_unit)
return None if converter is unit_scale_converter else converter |
Wave number conversion w.r.t. wavelength, freq, and energy. | def test_spectral4(in_val, in_unit):
"""Wave number conversion w.r.t. wavelength, freq, and energy."""
# Spectroscopic and angular
out_units = [u.micron**-1, u.radian / u.micron]
answers = [[1e5, 2.0, 1.0], [6.28318531e05, 12.5663706, 6.28318531]]
for out_unit, ans in zip(out_units, answers):
# Forward
a = in_unit.to(out_unit, in_val, u.spectral())
assert_allclose(a, ans)
# Backward
b = out_unit.to(in_unit, ans, u.spectral())
assert_allclose(b, in_val) |
PHOTLAM and PHOTNU conversions. | def test_spectraldensity4():
"""PHOTLAM and PHOTNU conversions."""
flam = u.erg / (u.cm**2 * u.s * u.AA)
fnu = u.erg / (u.cm**2 * u.s * u.Hz)
photlam = u.photon / (u.cm**2 * u.s * u.AA)
photnu = u.photon / (u.cm**2 * u.s * u.Hz)
wave = u.Quantity([4956.8, 4959.55, 4962.3], u.AA)
flux_photlam = [9.7654e-3, 1.003896e-2, 9.78473e-3]
flux_photnu = [8.00335589e-14, 8.23668949e-14, 8.03700310e-14]
flux_flam = [3.9135e-14, 4.0209e-14, 3.9169e-14]
flux_fnu = [3.20735792e-25, 3.29903646e-25, 3.21727226e-25]
flux_jy = [3.20735792e-2, 3.29903646e-2, 3.21727226e-2]
flux_stmag = [12.41858665, 12.38919182, 12.41764379]
flux_abmag = [12.63463143, 12.60403221, 12.63128047]
# PHOTLAM <--> FLAM
assert_allclose(
photlam.to(flam, flux_photlam, u.spectral_density(wave)), flux_flam, rtol=1e-6
)
assert_allclose(
flam.to(photlam, flux_flam, u.spectral_density(wave)), flux_photlam, rtol=1e-6
)
# PHOTLAM <--> FNU
assert_allclose(
photlam.to(fnu, flux_photlam, u.spectral_density(wave)), flux_fnu, rtol=1e-6
)
assert_allclose(
fnu.to(photlam, flux_fnu, u.spectral_density(wave)), flux_photlam, rtol=1e-6
)
# PHOTLAM <--> Jy
assert_allclose(
photlam.to(u.Jy, flux_photlam, u.spectral_density(wave)), flux_jy, rtol=1e-6
)
assert_allclose(
u.Jy.to(photlam, flux_jy, u.spectral_density(wave)), flux_photlam, rtol=1e-6
)
# PHOTLAM <--> PHOTNU
assert_allclose(
photlam.to(photnu, flux_photlam, u.spectral_density(wave)),
flux_photnu,
rtol=1e-6,
)
assert_allclose(
photnu.to(photlam, flux_photnu, u.spectral_density(wave)),
flux_photlam,
rtol=1e-6,
)
# PHOTNU <--> FNU
assert_allclose(
photnu.to(fnu, flux_photnu, u.spectral_density(wave)), flux_fnu, rtol=1e-6
)
assert_allclose(
fnu.to(photnu, flux_fnu, u.spectral_density(wave)), flux_photnu, rtol=1e-6
)
# PHOTNU <--> FLAM
assert_allclose(
photnu.to(flam, flux_photnu, u.spectral_density(wave)), flux_flam, rtol=1e-6
)
assert_allclose(
flam.to(photnu, flux_flam, u.spectral_density(wave)), flux_photnu, rtol=1e-6
)
# PHOTLAM <--> STMAG
assert_allclose(
photlam.to(u.STmag, flux_photlam, u.spectral_density(wave)),
flux_stmag,
rtol=1e-6,
)
assert_allclose(
u.STmag.to(photlam, flux_stmag, u.spectral_density(wave)),
flux_photlam,
rtol=1e-6,
)
# PHOTLAM <--> ABMAG
assert_allclose(
photlam.to(u.ABmag, flux_photlam, u.spectral_density(wave)),
flux_abmag,
rtol=1e-6,
)
assert_allclose(
u.ABmag.to(photlam, flux_abmag, u.spectral_density(wave)),
flux_photlam,
rtol=1e-6,
) |
Test photon luminosity density conversions. | def test_spectraldensity5():
"""Test photon luminosity density conversions."""
L_la = u.erg / (u.s * u.AA)
L_nu = u.erg / (u.s * u.Hz)
phot_L_la = u.photon / (u.s * u.AA)
phot_L_nu = u.photon / (u.s * u.Hz)
wave = u.Quantity([4956.8, 4959.55, 4962.3], u.AA)
flux_phot_L_la = [9.7654e-3, 1.003896e-2, 9.78473e-3]
flux_phot_L_nu = [8.00335589e-14, 8.23668949e-14, 8.03700310e-14]
flux_L_la = [3.9135e-14, 4.0209e-14, 3.9169e-14]
flux_L_nu = [3.20735792e-25, 3.29903646e-25, 3.21727226e-25]
# PHOTLAM <--> FLAM
assert_allclose(
phot_L_la.to(L_la, flux_phot_L_la, u.spectral_density(wave)),
flux_L_la,
rtol=1e-6,
)
assert_allclose(
L_la.to(phot_L_la, flux_L_la, u.spectral_density(wave)),
flux_phot_L_la,
rtol=1e-6,
)
# PHOTLAM <--> FNU
assert_allclose(
phot_L_la.to(L_nu, flux_phot_L_la, u.spectral_density(wave)),
flux_L_nu,
rtol=1e-6,
)
assert_allclose(
L_nu.to(phot_L_la, flux_L_nu, u.spectral_density(wave)),
flux_phot_L_la,
rtol=1e-6,
)
# PHOTLAM <--> PHOTNU
assert_allclose(
phot_L_la.to(phot_L_nu, flux_phot_L_la, u.spectral_density(wave)),
flux_phot_L_nu,
rtol=1e-6,
)
assert_allclose(
phot_L_nu.to(phot_L_la, flux_phot_L_nu, u.spectral_density(wave)),
flux_phot_L_la,
rtol=1e-6,
)
# PHOTNU <--> FNU
assert_allclose(
phot_L_nu.to(L_nu, flux_phot_L_nu, u.spectral_density(wave)),
flux_L_nu,
rtol=1e-6,
)
assert_allclose(
L_nu.to(phot_L_nu, flux_L_nu, u.spectral_density(wave)),
flux_phot_L_nu,
rtol=1e-6,
)
# PHOTNU <--> FLAM
assert_allclose(
phot_L_nu.to(L_la, flux_phot_L_nu, u.spectral_density(wave)),
flux_L_la,
rtol=1e-6,
)
assert_allclose(
L_la.to(phot_L_nu, flux_L_la, u.spectral_density(wave)),
flux_phot_L_nu,
rtol=1e-6,
) |
Test surface brightness conversions. | def test_spectraldensity6():
"""Test surface brightness conversions."""
slam = u.erg / (u.cm**2 * u.s * u.AA * u.sr)
snu = u.erg / (u.cm**2 * u.s * u.Hz * u.sr)
wave = u.Quantity([4956.8, 4959.55, 4962.3], u.AA)
sb_flam = [3.9135e-14, 4.0209e-14, 3.9169e-14]
sb_fnu = [3.20735792e-25, 3.29903646e-25, 3.21727226e-25]
# S(nu) <--> S(lambda)
assert_allclose(snu.to(slam, sb_fnu, u.spectral_density(wave)), sb_flam, rtol=1e-6)
assert_allclose(slam.to(snu, sb_flam, u.spectral_density(wave)), sb_fnu, rtol=1e-6) |
Not allowed to succeed as
per https://github.com/astropy/astropy/pull/10015 | def test_spectraldensity_not_allowed(from_unit, to_unit):
"""Not allowed to succeed as
per https://github.com/astropy/astropy/pull/10015
"""
with pytest.raises(u.UnitConversionError, match="not convertible"):
from_unit.to(to_unit, 1, u.spectral_density(1 * u.AA))
# The other way
with pytest.raises(u.UnitConversionError, match="not convertible"):
to_unit.to(from_unit, 1, u.spectral_density(1 * u.AA)) |
Regression test for #5350. This failed with a decoding error as
μas could not be represented in ascii. | def test_cds_non_ascii_unit():
"""Regression test for #5350. This failed with a decoding error as
μas could not be represented in ascii."""
from astropy.units import cds
with cds.enable():
u.radian.find_equivalent_units(include_prefix_units=True) |
Issue #436. | def test_console_out():
"""
Issue #436.
"""
u.Jy.decompose().to_string("console") |
Test function raises TypeError on bad input.
This instead of returning None, see gh-11825. | def test_fits_to_string_function_error():
"""Test function raises TypeError on bad input.
This instead of returning None, see gh-11825.
"""
with pytest.raises(TypeError, match="unit argument must be"):
u_format.Fits.to_string(None) |
Scale just off unity at machine precision level is OK.
Ensures #748 does not recur | def test_scale_effectively_unity():
"""Scale just off unity at machine precision level is OK.
Ensures #748 does not recur
"""
a = (3.0 * u.N).cgs
assert is_effectively_unity(a.unit.scale)
assert len(a.__repr__().split()) == 3 |
Test that the % unit is properly recognized. Since % is a special
symbol, this goes slightly beyond the round-tripping tested above. | def test_percent():
"""Test that the % unit is properly recognized. Since % is a special
symbol, this goes slightly beyond the round-tripping tested above."""
assert u.Unit("%") == u.percent == u.Unit(0.01)
assert u.Unit("%", format="cds") == u.Unit(0.01)
assert u.Unit(0.01).to_string("cds") == "%"
with pytest.raises(ValueError):
u.Unit("%", format="fits")
with pytest.raises(ValueError):
u.Unit("%", format="vounit") |
Test that scaled dimensionless units are properly recognized in generic
and CDS, but not in fits and vounit. | def test_scaled_dimensionless():
"""Test that scaled dimensionless units are properly recognized in generic
and CDS, but not in fits and vounit."""
assert u.Unit("0.1") == u.Unit(0.1) == 0.1 * u.dimensionless_unscaled
assert u.Unit("1.e-4") == u.Unit(1.0e-4)
assert u.Unit("10-4", format="cds") == u.Unit(1.0e-4)
assert u.Unit("10+8").to_string("cds") == "10+8"
with pytest.raises(ValueError):
u.Unit(0.15).to_string("fits")
assert u.Unit(0.1).to_string("fits") == "10**-1"
with pytest.raises(ValueError):
u.Unit(0.1).to_string("vounit") |
Regression test for #5870, #8699, #9218, #14403; avoid double superscripts. | def test_double_superscript(unit, latex, unicode):
"""Regression test for #5870, #8699, #9218, #14403; avoid double superscripts."""
assert unit.to_string("latex") == latex
assert unit.to_string("unicode") == unicode |
Regression test for gh-911 and #14419. | def test_no_prefix_superscript():
"""Regression test for gh-911 and #14419."""
assert u.mdeg.to_string("latex") == r"$\mathrm{mdeg}$"
assert u.narcmin.to_string("latex") == r"$\mathrm{narcmin}$"
assert u.parcsec.to_string("latex") == r"$\mathrm{parcsec}$"
assert u.mdeg.to_string("unicode") == "mdeg"
assert u.narcmin.to_string("unicode") == "narcmin"
assert u.parcsec.to_string("unicode") == "parcsec" |
Regression test for #9279 - powers should not be oversimplified. | def test_powers(power, expected):
"""Regression test for #9279 - powers should not be oversimplified."""
unit = u.m**power
s = unit.to_string()
assert s == expected
assert unit == s |
Ensure round-tripping; see #5015 | def test_predefined_string_roundtrip():
"""Ensure round-tripping; see #5015"""
assert u.Unit(u.STmag.to_string()) == u.STmag
assert u.Unit(u.ABmag.to_string()) == u.ABmag
assert u.Unit(u.M_bol.to_string()) == u.M_bol
assert u.Unit(u.m_bol.to_string()) == u.m_bol |
Check __ne__ works (regression for #5342). | def test_inequality():
"""Check __ne__ works (regression for #5342)."""
lu1 = u.mag(u.Jy)
lu2 = u.dex(u.Jy)
lu3 = u.mag(u.Jy**2)
lu4 = lu3 - lu1
assert lu1 != lu2
assert lu1 != lu3
assert lu1 == lu4 |
Ensures we can convert from regular quantities. | def test_conversion_to_and_from_physical_quantities():
"""Ensures we can convert from regular quantities."""
mst = [10.0, 12.0, 14.0] * u.STmag
flux_lambda = mst.physical
mst_roundtrip = flux_lambda.to(u.STmag)
# check we return a logquantity; see #5178.
assert isinstance(mst_roundtrip, u.Magnitude)
assert mst_roundtrip.unit == mst.unit
assert_allclose(mst_roundtrip.value, mst.value)
wave = [4956.8, 4959.55, 4962.3] * u.AA
flux_nu = mst.to(u.Jy, equivalencies=u.spectral_density(wave))
mst_roundtrip2 = flux_nu.to(u.STmag, u.spectral_density(wave))
assert isinstance(mst_roundtrip2, u.Magnitude)
assert mst_roundtrip2.unit == mst.unit
assert_allclose(mst_roundtrip2.value, mst.value) |
Test that the `physical_type` attribute of `u.Unit` objects provides
the expected physical type for various units.
Many of these tests are used to test backwards compatibility. | def test_physical_type_names(unit, physical_type):
"""
Test that the `physical_type` attribute of `u.Unit` objects provides
the expected physical type for various units.
Many of these tests are used to test backwards compatibility.
"""
assert unit.physical_type == physical_type, (
f"{unit!r}.physical_type was expected to return "
f"{physical_type!r}, but instead returned {unit.physical_type!r}."
) |
Test different ways of getting a physical type. | def test_getting_physical_type(physical_type_representation, physical_type_name):
"""Test different ways of getting a physical type."""
physical_type = physical.get_physical_type(physical_type_representation)
assert isinstance(physical_type, physical.PhysicalType)
assert physical_type == physical_type_name |
Test that `get_physical_type` raises appropriate exceptions when
provided with invalid arguments. | def test_getting_physical_type_exceptions(argument, exception):
"""
Test that `get_physical_type` raises appropriate exceptions when
provided with invalid arguments.
"""
with pytest.raises(exception):
physical.get_physical_type(argument) |
Test that `PhysicalType` instances cannot be cast into `Quantity`
objects. A failure in this test could be related to failures
in subsequent tests. | def test_physical_type_cannot_become_quantity():
"""
Test that `PhysicalType` instances cannot be cast into `Quantity`
objects. A failure in this test could be related to failures
in subsequent tests.
"""
with pytest.raises(TypeError):
u.Quantity(u.m.physical_type, u.m) |
Test that `PhysicalType` dunder methods that require another
argument behave as intended. | def test_physical_type_operations(left, right, operator, expected):
"""
Test that `PhysicalType` dunder methods that require another
argument behave as intended.
"""
assert getattr(left, operator)(right) == expected |
Test making a `physical.PhysicalType` instance into a `set`. | def test_physical_type_as_set(unit, expected_set):
"""Test making a `physical.PhysicalType` instance into a `set`."""
resulting_set = set(unit.physical_type)
assert resulting_set == expected_set |
Test iterating through different physical type names. | def test_physical_type_iteration():
"""Test iterating through different physical type names."""
physical_type_names = list(pressure)
assert physical_type_names == ["energy density", "pressure", "stress"] |
Test that `in` works as expected for `PhysicalType` objects with one
or multiple names. | def test_physical_type_in():
"""
Test that `in` works as expected for `PhysicalType` objects with one
or multiple names.
"""
assert "length" in length
assert "pressure" in pressure |
Test that `physical.PhysicalType` instances for units of the same
dimensionality are equal. | def test_physical_type_instance_equality(unit1, unit2):
"""
Test that `physical.PhysicalType` instances for units of the same
dimensionality are equal.
"""
assert (unit1.physical_type == unit2.physical_type) is True
assert (unit1.physical_type != unit2.physical_type) is False |
Test that `get_physical_type` retrieves the same `PhysicalType`
instances for equivalent physical types, except for unknown types
which are not cataloged. | def test_get_physical_type_equivalent_pairs(unit1, unit2):
"""
Test that `get_physical_type` retrieves the same `PhysicalType`
instances for equivalent physical types, except for unknown types
which are not cataloged.
"""
physical_type1 = physical.get_physical_type(unit1)
physical_type2 = physical.get_physical_type(unit2)
assert physical_type1 == physical_type2
if physical_type1 != "unknown":
assert physical_type1 is physical_type2 |
Test that `physical.PhysicalType` instances for units with different
dimensionality are considered unequal. | def test_physical_type_instance_inequality(unit1, unit2):
"""
Test that `physical.PhysicalType` instances for units with different
dimensionality are considered unequal.
"""
physical_type1 = physical.PhysicalType(unit1, "ptype1")
physical_type2 = physical.PhysicalType(unit2, "ptype2")
assert (physical_type1 != physical_type2) is True
assert (physical_type1 == physical_type2) is False |
Test using `str` on a `PhysicalType` instance. | def test_physical_type_str(physical_type, expected_str):
"""Test using `str` on a `PhysicalType` instance."""
assert str(physical_type) == expected_str |
Test using `repr` on a `PhysicalType` instance. | def physical_type_repr(physical_type, expected_repr):
"""Test using `repr` on a `PhysicalType` instance."""
assert repr(physical_type) == expected_repr |
Test that a `PhysicalType` instance can be used as a dict key. | def test_physical_type_hash():
"""Test that a `PhysicalType` instance can be used as a dict key."""
dictionary = {length: 42}
assert dictionary[length] == 42 |
Test that multiplication of a physical type returns `NotImplemented`
when attempted for an invalid type. | def test_physical_type_multiplication(multiplicand):
"""
Test that multiplication of a physical type returns `NotImplemented`
when attempted for an invalid type.
"""
with pytest.raises(TypeError):
length * multiplicand |
Test basic functionality for the physical type of an unrecognized
unit. | def test_unrecognized_unit_physical_type():
"""
Test basic functionality for the physical type of an unrecognized
unit.
"""
unrecognized_unit = u.Unit("parrot", parse_strict="silent")
physical_type = unrecognized_unit.physical_type
assert isinstance(physical_type, physical.PhysicalType)
assert physical_type == "unknown" |
Test that `PhysicalType` cannot be instantiated when one of the
supplied names is not a string, while making sure that the physical
type for the unit remains unknown. | def test_invalid_physical_types(invalid_input):
"""
Test that `PhysicalType` cannot be instantiated when one of the
supplied names is not a string, while making sure that the physical
type for the unit remains unknown.
"""
obscure_unit = u.s**87
with pytest.raises(ValueError):
physical.PhysicalType(obscure_unit, invalid_input)
assert obscure_unit.physical_type == "unknown" |
Regression test for bug #1163
If decompose was called multiple times on a Quantity with an array and a
scale != 1, the result changed every time. This is because the value was
being referenced not copied, then modified, which changed the original
value. | def test_decompose_regression():
"""
Regression test for bug #1163
If decompose was called multiple times on a Quantity with an array and a
scale != 1, the result changed every time. This is because the value was
being referenced not copied, then modified, which changed the original
value.
"""
q = np.array([1, 2, 3]) * u.m / (2.0 * u.km)
assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015]))
assert np.all(q == np.array([1, 2, 3]) * u.m / (2.0 * u.km))
assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) |
Test using quantites with array values | def test_arrays():
"""
Test using quantites with array values
"""
qsec = u.Quantity(np.arange(10), u.second)
assert isinstance(qsec.value, np.ndarray)
assert not qsec.isscalar
# len and indexing should work for arrays
assert len(qsec) == len(qsec.value)
qsecsub25 = qsec[2:5]
assert qsecsub25.unit == qsec.unit
assert isinstance(qsecsub25, u.Quantity)
assert len(qsecsub25) == 3
# make sure isscalar, len, and indexing behave correctly for non-arrays.
qsecnotarray = u.Quantity(10.0, u.second)
assert qsecnotarray.isscalar
with pytest.raises(TypeError):
len(qsecnotarray)
with pytest.raises(TypeError):
qsecnotarray[0]
qseclen0array = u.Quantity(np.array(10), u.second, dtype=int)
# 0d numpy array should act basically like a scalar
assert qseclen0array.isscalar
with pytest.raises(TypeError):
len(qseclen0array)
with pytest.raises(TypeError):
qseclen0array[0]
assert isinstance(qseclen0array.value, numbers.Integral)
a = np.array(
[(1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0)],
dtype=[("x", float), ("y", float), ("z", float)],
)
qkpc = u.Quantity(a, u.kpc)
assert not qkpc.isscalar
qkpc0 = qkpc[0]
assert qkpc0.value == a[0]
assert qkpc0.unit == qkpc.unit
assert isinstance(qkpc0, u.Quantity)
assert qkpc0.isscalar
qkpcx = qkpc["x"]
assert np.all(qkpcx.value == a["x"])
assert qkpcx.unit == qkpc.unit
assert isinstance(qkpcx, u.Quantity)
assert not qkpcx.isscalar
qkpcx1 = qkpc["x"][1]
assert qkpcx1.unit == qkpc.unit
assert isinstance(qkpcx1, u.Quantity)
assert qkpcx1.isscalar
qkpc1x = qkpc[1]["x"]
assert qkpc1x.isscalar
assert qkpc1x == qkpcx1
# can also create from lists, will auto-convert to arrays
qsec = u.Quantity(list(range(10)), u.second)
assert isinstance(qsec.value, np.ndarray)
# quantity math should work with arrays
assert_array_equal((qsec * 2).value, (np.arange(10) * 2))
assert_array_equal((qsec / 2).value, (np.arange(10) / 2))
# quantity addition/subtraction should *not* work with arrays b/c unit
# ambiguous
with pytest.raises(u.UnitsError):
assert_array_equal((qsec + 2).value, (np.arange(10) + 2))
with pytest.raises(u.UnitsError):
assert_array_equal((qsec - 2).value, (np.arange(10) + 2))
# should create by unit multiplication, too
qsec2 = np.arange(10) * u.second
qsec3 = u.second * np.arange(10)
assert np.all(qsec == qsec2)
assert np.all(qsec2 == qsec3)
# make sure numerical-converters fail when arrays are present
with pytest.raises(TypeError):
float(qsec)
with pytest.raises(TypeError):
int(qsec) |
Regression test from issue #679 | def test_inverse_quantity():
"""
Regression test from issue #679
"""
q = u.Quantity(4.0, u.meter / u.second)
qot = q / 2
toq = 2 / q
npqot = q / np.array(2)
assert npqot.value == 2.0
assert npqot.unit == (u.meter / u.second)
assert qot.value == 2.0
assert qot.unit == (u.meter / u.second)
assert toq.value == 0.5
assert toq.unit == (u.second / u.meter) |
Regressiont est for issue #878.
Scalar quantities should not be iterable and should raise a type error on
iteration. | def test_quantity_iterability():
"""Regressiont est for issue #878.
Scalar quantities should not be iterable and should raise a type error on
iteration.
"""
q1 = [15.0, 17.0] * u.m
assert isiterable(q1)
q2 = next(iter(q1))
assert q2 == 15.0 * u.m
assert not isiterable(q2)
pytest.raises(TypeError, iter, q2) |
A regression test to ensure that numpy scalars are correctly compared
(which originally failed due to the lack of ``__array_priority__``). | def test_equality_numpy_scalar():
"""
A regression test to ensure that numpy scalars are correctly compared
(which originally failed due to the lack of ``__array_priority__``).
"""
assert 10 != 10.0 * u.m
assert np.int64(10) != 10 * u.m
assert 10 * u.m != np.int64(10) |
Testing pickleability of quantity | def test_quantity_pickelability():
"""
Testing pickleability of quantity
"""
q1 = np.arange(10) * u.m
q2 = pickle.loads(pickle.dumps(q1))
assert np.all(q1.value == q2.value)
assert q1.unit.is_equivalent(q2.unit)
assert q1.unit == q2.unit |
Checks that units from tables are respected when converted to a Quantity.
This also generically checks the use of *anything* with a `unit` attribute
passed into Quantity | def test_quantity_from_table():
"""
Checks that units from tables are respected when converted to a Quantity.
This also generically checks the use of *anything* with a `unit` attribute
passed into Quantity
"""
from astropy.table import Table
t = Table(data=[np.arange(5), np.arange(5)], names=["a", "b"])
t["a"].unit = u.kpc
qa = u.Quantity(t["a"])
assert qa.unit == u.kpc
assert_array_equal(qa.value, t["a"])
qb = u.Quantity(t["b"])
assert qb.unit == u.dimensionless_unscaled
assert_array_equal(qb.value, t["b"])
# This does *not* auto-convert, because it's not necessarily obvious that's
# desired. Instead we revert to standard `Quantity` behavior
qap = u.Quantity(t["a"], u.pc)
assert qap.unit == u.pc
assert_array_equal(qap.value, t["a"] * 1000)
qbp = u.Quantity(t["b"], u.pc)
assert qbp.unit == u.pc
assert_array_equal(qbp.value, t["b"])
# Also check with a function unit (regression test for gh-8430)
t["a"].unit = u.dex(u.cm / u.s**2)
fq = u.Dex(t["a"])
assert fq.unit == u.dex(u.cm / u.s**2)
assert_array_equal(fq.value, t["a"])
fq2 = u.Quantity(t["a"], subok=True)
assert isinstance(fq2, u.Dex)
assert fq2.unit == u.dex(u.cm / u.s**2)
assert_array_equal(fq2.value, t["a"])
with pytest.raises(u.UnitTypeError):
u.Quantity(t["a"]) |
Test Quantity.insert method. This does not test the full capabilities
of the underlying np.insert, but hits the key functionality for
Quantity. | def test_insert():
"""
Test Quantity.insert method. This does not test the full capabilities
of the underlying np.insert, but hits the key functionality for
Quantity.
"""
q = [1, 2] * u.m
# Insert a compatible float with different units
q2 = q.insert(0, 1 * u.km)
assert np.all(q2.value == [1000, 1, 2])
assert q2.unit is u.m
assert q2.dtype.kind == "f"
if minversion(np, "1.8.0"):
q2 = q.insert(1, [1, 2] * u.km)
assert np.all(q2.value == [1, 1000, 2000, 2])
assert q2.unit is u.m
# Cannot convert 1.5 * u.s to m
with pytest.raises(u.UnitsError):
q.insert(1, 1.5 * u.s)
# Tests with multi-dim quantity
q = [[1, 2], [3, 4]] * u.m
q2 = q.insert(1, [10, 20] * u.m, axis=0)
assert np.all(q2.value == [[1, 2], [10, 20], [3, 4]])
q2 = q.insert(1, [10, 20] * u.m, axis=1)
assert np.all(q2.value == [[1, 10, 2], [3, 20, 4]])
q2 = q.insert(1, 10 * u.m, axis=1)
assert np.all(q2.value == [[1, 10, 2], [3, 10, 4]]) |
Test print/repr of object arrays of Quantity objects with different
units.
Regression test for the issue first reported in
https://github.com/astropy/astropy/issues/3777 | def test_repr_array_of_quantity():
"""
Test print/repr of object arrays of Quantity objects with different
units.
Regression test for the issue first reported in
https://github.com/astropy/astropy/issues/3777
"""
a = np.array([1 * u.m, 2 * u.s], dtype=object)
assert repr(a) == "array([<Quantity 1. m>, <Quantity 2. s>], dtype=object)"
assert str(a) == "[<Quantity 1. m> <Quantity 2. s>]" |
Ensure we don't break masked Quantity representation. | def test_masked_quantity_str_repr():
"""Ensure we don't break masked Quantity representation."""
# Really, masked quantities do not work well, but at least let the
# basics work.
masked_quantity = np.ma.array([1, 2, 3, 4] * u.kg, mask=[True, False, True, False])
str(masked_quantity)
repr(masked_quantity) |
Test annotations that are not unit related are ignored.
This test passes if the function works. | def test_ignore_generic_type_annotations():
"""Test annotations that are not unit related are ignored.
This test passes if the function works.
"""
# one unit, one not (should be ignored)
@u.quantity_input
def func(x: u.m, y: str):
return x, y
i_q, i_str = 2 * u.m, "cool string"
o_q, o_str = func(i_q, i_str) # if this doesn't fail, it worked.
assert i_q == o_q
assert i_str == o_str |
When dimensionless_unscaled is an allowed unit, numbers and numeric numpy
arrays are allowed through | def test_allow_dimensionless_numeric(val):
"""
When dimensionless_unscaled is an allowed unit, numbers and numeric numpy
arrays are allowed through
"""
@u.quantity_input(velocity=[u.km / u.s, u.dimensionless_unscaled])
def myfunc(velocity):
return velocity
assert np.all(myfunc(val) == val) |
When dimensionless_unscaled is an allowed unit, but we are being strict,
don't allow numbers and numeric numpy arrays through | def test_allow_dimensionless_numeric_strict(val):
"""
When dimensionless_unscaled is an allowed unit, but we are being strict,
don't allow numbers and numeric numpy arrays through
"""
@u.quantity_input(
velocity=[u.km / u.s, u.dimensionless_unscaled], strict_dimensionless=True
)
def myfunc(velocity):
return velocity
with pytest.raises(TypeError):
assert myfunc(val) |
When dimensionless_unscaled is the only allowed unit, don't let input with
non-dimensionless units through | def test_dimensionless_with_nondimensionless_input(val):
"""
When dimensionless_unscaled is the only allowed unit, don't let input with
non-dimensionless units through
"""
@u.quantity_input(x=u.dimensionless_unscaled)
def myfunc(x):
return x
with pytest.raises(u.UnitsError):
myfunc(val) |
Test when annotation looks like a Quantity[X], but isn't. | def test_annotated_not_quantity():
"""Test when annotation looks like a Quantity[X], but isn't."""
@u.quantity_input()
def myfunc(x: typing.Annotated[object, u.m]):
return x
# nothing happens when wrong unit is passed
assert myfunc(1) == 1
assert myfunc(1 * u.m) == 1 * u.m
assert myfunc(1 * u.s) == 1 * u.s |
Test when annotation looks like a Quantity[X], but the unit's wrong. | def test_annotated_not_unit():
"""Test when annotation looks like a Quantity[X], but the unit's wrong."""
@u.quantity_input()
def myfunc(x: typing.Annotated[u.Quantity, object()]):
return x
# nothing happens when wrong unit is passed
assert myfunc(1) == 1
assert myfunc(1 * u.m) == 1 * u.m
assert myfunc(1 * u.s) == 1 * u.s |
Mimic routine of erfa/src/t_erfa_c.c (to help copy & paste) | def vvd(val, valok, dval, func, test, status):
"""Mimic routine of erfa/src/t_erfa_c.c (to help copy & paste)"""
assert u.allclose(val, valok * val.unit, atol=dval * val.unit) |
Identify all functions that are covered by tests.
Looks through the namespace (typically, ``locals()``) for classes that
have ``test_<name>`` members, and returns a set of the functions with
those names. By default, the names are looked up on `numpy`, but each
class can override this by having a ``tested_module`` attribute (e.g.,
``tested_module = np.linalg``). | def get_covered_functions(ns: dict) -> set[FunctionType]:
"""Identify all functions that are covered by tests.
Looks through the namespace (typically, ``locals()``) for classes that
have ``test_<name>`` members, and returns a set of the functions with
those names. By default, the names are looked up on `numpy`, but each
class can override this by having a ``tested_module`` attribute (e.g.,
``tested_module = np.linalg``).
"""
covered = set()
for test_cls in filter(inspect.isclass, ns.values()):
module = getattr(test_cls, "tested_module", np)
covered |= {
function
for k, v in test_cls.__dict__.items()
if inspect.isfunction(v)
and k.startswith("test_")
and (function := getattr(module, k.replace("test_", ""), None)) is not None
}
return covered |
Issue #1150: Test for conversion of dimensionless quantities
to the SI system | def test_dimensionless_to_si():
"""
Issue #1150: Test for conversion of dimensionless quantities
to the SI system
"""
testunit = (1.0 * u.kpc) / (1.0 * u.Mpc)
assert testunit.unit.physical_type == "dimensionless"
assert_allclose(testunit.si, 0.001) |
Issue #1150: Test for conversion of dimensionless quantities
to the CGS system | def test_dimensionless_to_cgs():
"""
Issue #1150: Test for conversion of dimensionless quantities
to the CGS system
"""
testunit = (1.0 * u.m) / (1.0 * u.km)
assert testunit.unit.physical_type == "dimensionless"
assert_allclose(testunit.cgs, 0.001) |
Issue #599 | def test_steradian():
"""
Issue #599
"""
assert u.sr.is_equivalent(u.rad * u.rad)
results = u.sr.compose(units=u.cgs.bases)
assert results[0].bases[0] is u.rad
results = u.sr.compose(units=u.cgs.__dict__)
assert results[0].bases[0] is u.sr |
From issue #576 | def test_decompose_bases():
"""
From issue #576
"""
from astropy.constants import e
from astropy.units import cgs
d = e.esu.unit.decompose(bases=cgs.bases)
assert d._bases == [u.cm, u.g, u.s]
assert d._powers == [Fraction(3, 2), 0.5, -1]
assert d._scale == 1.0 |
Check units that are not official derived units.
Should not appear on its own or as part of a composite unit. | def test_to_si():
"""Check units that are not official derived units.
Should not appear on its own or as part of a composite unit.
"""
# TODO: extend to all units not listed in Tables 1--6 of
# https://physics.nist.gov/cuu/Units/units.html
# See gh-10585.
# This was always the case
assert u.bar.si is not u.bar
# But this used to fail.
assert u.bar not in (u.kg / (u.s**2 * u.sr * u.nm)).si._bases |
Issue #672 | def test_long_int():
"""
Issue #672
"""
sigma = 10**21 * u.M_p / u.cm**2
sigma.to(u.M_sun / u.pc**2) |
Regression test for #744
A logic issue in the units code meant that big endian arrays could not be
converted because the dtype is '>f4', not 'float32', and the code was
looking for the strings 'float' or 'int'. | def test_endian_independence():
"""
Regression test for #744
A logic issue in the units code meant that big endian arrays could not be
converted because the dtype is '>f4', not 'float32', and the code was
looking for the strings 'float' or 'int'.
"""
for endian in ["<", ">"]:
for ntype in ["i", "f"]:
for byte in ["4", "8"]:
x = np.array([1, 2, 3], dtype=(endian + ntype + byte))
u.m.to(u.cm, x) |
Issue #863 | def test_radian_base():
"""
Issue #863
"""
assert (1 * u.degree).si.unit == u.rad |
We cannot really test between sessions easily, so fake it.
This test can be changed if the pickle protocol or the code
changes enough that it no longer works. | def test_pickle_between_sessions():
"""We cannot really test between sessions easily, so fake it.
This test can be changed if the pickle protocol or the code
changes enough that it no longer works.
"""
hash_m = hash(u.m)
unit = pickle.loads(
b"\x80\x04\x95\xd6\x00\x00\x00\x00\x00\x00\x00\x8c\x12"
b"astropy.units.core\x94\x8c\x1a_recreate_irreducible_unit"
b"\x94\x93\x94h\x00\x8c\x0fIrreducibleUnit\x94\x93\x94]\x94"
b"(\x8c\x01m\x94\x8c\x05meter\x94e\x88\x87\x94R\x94}\x94(\x8c\x06"
b"_names\x94]\x94(h\x06h\x07e\x8c\x0c_short_names"
b"\x94]\x94h\x06a\x8c\x0b_long_names\x94]\x94h\x07a\x8c\x07"
b"_format\x94}\x94\x8c\x07__doc__\x94\x8c "
b"meter: base unit of length in SI\x94ub."
)
assert unit is u.m
assert hash(u.m) == hash_m |
Tests private attribute since the problem with _hash being pickled
and restored only appeared if the unpickling was done in another
session, for which the hash no longer was valid, and it is difficult
to mimic separate sessions in a simple test. See gh-11872. | def test_pickle_does_not_keep_memoized_hash(unit):
"""
Tests private attribute since the problem with _hash being pickled
and restored only appeared if the unpickling was done in another
session, for which the hash no longer was valid, and it is difficult
to mimic separate sessions in a simple test. See gh-11872.
"""
unit_hash = hash(unit)
assert unit._hash is not None
unit_copy = pickle.loads(pickle.dumps(unit))
# unit is not registered so we get a copy.
assert unit_copy is not unit
assert unit_copy._hash is None
assert hash(unit_copy) == unit_hash
with u.add_enabled_units([unit]):
# unit is registered, so we get a reference.
unit_ref = pickle.loads(pickle.dumps(unit))
if isinstance(unit, u.IrreducibleUnit):
assert unit_ref is unit
else:
assert unit_ref is not unit
# pickle.load used to override the hash, although in this case
# it would be the same anyway, so not clear this tests much.
assert hash(unit) == unit_hash |
Issue #2047 | def test_pickle_unrecognized_unit():
"""
Issue #2047
"""
a = u.Unit("asdf", parse_strict="silent")
pickle.loads(pickle.dumps(a)) |
Check that multiplication with strings produces the correct unit. | def test_unit_multiplication_with_string():
"""Check that multiplication with strings produces the correct unit."""
u1 = u.cm
us = "kg"
assert us * u1 == u.Unit(us) * u1
assert u1 * us == u1 * u.Unit(us) |
Check that multiplication with strings produces the correct unit. | def test_unit_division_by_string():
"""Check that multiplication with strings produces the correct unit."""
u1 = u.cm
us = "kg"
assert us / u1 == u.Unit(us) / u1
assert u1 / us == u1 / u.Unit(us) |
See #1616. | def test_sorted_bases():
"""See #1616."""
assert (u.m * u.Jy).bases == (u.Jy * u.m).bases |
See #1543 | def test_megabit():
"""See #1543"""
assert u.Mbit is u.Mb
assert u.megabit is u.Mb
assert u.Mbyte is u.MB
assert u.megabyte is u.MB |
See #1576 | def test_composite_unit_get_format_name():
"""See #1576"""
unit1 = u.Unit("nrad/s")
unit2 = u.Unit("Hz(1/2)")
assert str(u.CompositeUnit(1, [unit1, unit2], [1, -1])) == "nrad / (Hz(1/2) s)" |
See #1911. | def test_fits_hst_unit():
"""See #1911."""
with pytest.warns(u.UnitsWarning, match="multiple slashes") as w:
x = u.Unit("erg /s /cm**2 /angstrom")
assert x == u.erg * u.s**-1 * u.cm**-2 * u.angstrom**-1
assert len(w) == 1 |
Regression test for https://github.com/astropy/astropy/issues/3753 | def test_barn_prefixes():
"""Regression test for https://github.com/astropy/astropy/issues/3753"""
assert u.fbarn is u.femtobarn
assert u.pbarn is u.picobarn |
See #2069 | def test_fractional_powers():
"""See #2069"""
m = 1e9 * u.Msun
tH = 1.0 / (70.0 * u.km / u.s / u.Mpc)
vc = 200 * u.km / u.s
x = (c.G**2 * m**2 * tH.cgs) ** Fraction(1, 3) / vc
v1 = x.to("pc")
x = (c.G**2 * m**2 * tH) ** Fraction(1, 3) / vc
v2 = x.to("pc")
x = (c.G**2 * m**2 * tH.cgs) ** (1.0 / 3.0) / vc
v3 = x.to("pc")
x = (c.G**2 * m**2 * tH) ** (1.0 / 3.0) / vc
v4 = x.to("pc")
assert_allclose(v1, v2)
assert_allclose(v2, v3)
assert_allclose(v3, v4)
x = u.m ** (1.0 / 101.0)
assert isinstance(x.powers[0], float)
x = u.m ** (3.0 / 7.0)
assert isinstance(x.powers[0], Fraction)
assert x.powers[0].numerator == 3
assert x.powers[0].denominator == 7
x = u.cm ** Fraction(1, 2) * u.cm ** Fraction(2, 3)
assert isinstance(x.powers[0], Fraction)
assert x.powers[0] == Fraction(7, 6)
# Regression test for #9258 (avoid fractions with crazy denominators).
x = (u.TeV ** (-2.2)) ** (1 / -2.2)
assert isinstance(x.powers[0], int)
assert x.powers[0] == 1
x = (u.TeV ** (-2.2)) ** (1 / -6.6)
assert isinstance(x.powers[0], Fraction)
assert x.powers[0] == Fraction(1, 3) |
Test for a few units that the unit summary table correctly reports
whether or not that unit supports prefixes.
Regression test for https://github.com/astropy/astropy/issues/3835 | def test_unit_summary_prefixes():
"""
Test for a few units that the unit summary table correctly reports
whether or not that unit supports prefixes.
Regression test for https://github.com/astropy/astropy/issues/3835
"""
from astropy.units import astrophys
for summary in utils._iter_unit_summary(astrophys.__dict__):
unit, _, _, _, prefixes = summary
if unit.name == "lyr":
assert prefixes
elif unit.name == "pc":
assert prefixes
elif unit.name == "barn":
assert prefixes
elif unit.name == "cycle":
assert prefixes == "No"
elif unit.name == "spat":
assert prefixes == "No"
elif unit.name == "vox":
assert prefixes == "Yes" |
Test that order of bases is changed when raising to negative power.
Regression test for https://github.com/astropy/astropy/issues/8260 | def test_raise_to_negative_power():
"""Test that order of bases is changed when raising to negative power.
Regression test for https://github.com/astropy/astropy/issues/8260
"""
m2s2 = u.m**2 / u.s**2
spm = m2s2 ** (-1 / 2)
assert spm.bases == [u.s, u.m]
assert spm.powers == [1, -1]
assert spm == u.s / u.m |
Make a new function from an existing function but with the desired
signature.
The desired signature must of course be compatible with the arguments
actually accepted by the input function.
The ``args`` are strings that should be the names of the positional
arguments. ``kwargs`` can map names of keyword arguments to their
default values. It may be either a ``dict`` or a list of ``(keyword,
default)`` tuples.
If ``varargs`` is a string it is added to the positional arguments as
``*<varargs>``. Likewise ``varkwargs`` can be the name for a variable
keyword argument placeholder like ``**<varkwargs>``.
If not specified the name of the new function is taken from the original
function. Otherwise, the ``name`` argument can be used to specify a new
name.
Note, the names may only be valid Python variable names. | def make_function_with_signature(
func, args=(), kwargs={}, varargs=None, varkwargs=None, name=None
):
"""
Make a new function from an existing function but with the desired
signature.
The desired signature must of course be compatible with the arguments
actually accepted by the input function.
The ``args`` are strings that should be the names of the positional
arguments. ``kwargs`` can map names of keyword arguments to their
default values. It may be either a ``dict`` or a list of ``(keyword,
default)`` tuples.
If ``varargs`` is a string it is added to the positional arguments as
``*<varargs>``. Likewise ``varkwargs`` can be the name for a variable
keyword argument placeholder like ``**<varkwargs>``.
If not specified the name of the new function is taken from the original
function. Otherwise, the ``name`` argument can be used to specify a new
name.
Note, the names may only be valid Python variable names.
"""
pos_args = []
key_args = []
if isinstance(kwargs, dict):
iter_kwargs = kwargs.items()
else:
iter_kwargs = iter(kwargs)
# Check that all the argument names are valid
for item in (*args, *iter_kwargs):
if isinstance(item, tuple):
argname = item[0]
key_args.append(item)
else:
argname = item
pos_args.append(item)
if keyword.iskeyword(argname) or not _ARGNAME_RE.match(argname):
raise SyntaxError(f"invalid argument name: {argname}")
for item in (varargs, varkwargs):
if item is not None:
if keyword.iskeyword(item) or not _ARGNAME_RE.match(item):
raise SyntaxError(f"invalid argument name: {item}")
def_signature = [", ".join(pos_args)]
if varargs:
def_signature.append(f", *{varargs}")
call_signature = def_signature[:]
if name is None:
name = func.__name__
global_vars = {f"__{name}__func": func}
local_vars = {}
# Make local variables to handle setting the default args
for idx, item in enumerate(key_args):
key, value = item
default_var = f"_kwargs{idx}"
local_vars[default_var] = value
def_signature.append(f", {key}={default_var}")
call_signature.append(f", {key}={key}")
if varkwargs:
def_signature.append(f", **{varkwargs}")
call_signature.append(f", **{varkwargs}")
def_signature = "".join(def_signature).lstrip(", ")
call_signature = "".join(call_signature).lstrip(", ")
mod = find_current_module(2)
frm = inspect.currentframe().f_back
if mod:
filename = mod.__file__
modname = mod.__name__
if filename.endswith(".pyc"):
filename = os.path.splitext(filename)[0] + ".py"
else:
filename = "<string>"
modname = "__main__"
# Subtract 2 from the line number since the length of the template itself
# is two lines. Therefore we have to subtract those off in order for the
# pointer in tracebacks from __{name}__func to point to the right spot.
lineno = frm.f_lineno - 2
# The lstrip is in case there were *no* positional arguments (a rare case)
# in any context this will actually be used...
template = textwrap.dedent(
"""{0}\
def {name}({sig1}):
return __{name}__func({sig2})
""".format("\n" * lineno, name=name, sig1=def_signature, sig2=call_signature)
)
code = compile(template, filename, "single")
eval(code, global_vars, local_vars)
new_func = local_vars[name]
new_func.__module__ = modname
new_func.__doc__ = func.__doc__
return new_func |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.