Skip to content

Commit

Permalink
Make some kwargs-arguments named keyword-only arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
MSeifert04 committed Oct 10, 2017
1 parent 42932d1 commit f9f5087
Show file tree
Hide file tree
Showing 14 changed files with 47 additions and 80 deletions.
8 changes: 3 additions & 5 deletions astropy/coordinates/baseframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,14 +265,12 @@ class BaseCoordinateFrame(ShapedLikeNDArray, metaclass=FrameMeta):
frame_attributes = OrderedDict()
# Default empty frame_attributes dict

def __init__(self, *args, **kwargs):
copy = kwargs.pop('copy', True)
def __init__(self, *args, copy=True, representation=None,
differential_cls=None,**kwargs):
self._attr_names_with_defaults = []

# TODO: we should be able to deal with an instance, not just a
# class or string.
representation = kwargs.pop('representation', None)
differential_cls = kwargs.pop('differential_cls', None)
# class or string for representation and differential_cls.

if representation is not None or differential_cls is not None:

Expand Down
3 changes: 1 addition & 2 deletions astropy/coordinates/representation.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,9 +471,8 @@ class BaseRepresentation(BaseRepresentationOrDifferential,

recommended_units = {} # subclasses can override

def __init__(self, *args, **kwargs):
def __init__(self, *args, differentials=None, **kwargs):
# Handle any differentials passed in.
differentials = kwargs.pop('differentials', None)
super().__init__(*args, **kwargs)
self._differentials = self._validate_differentials(differentials)

Expand Down
3 changes: 1 addition & 2 deletions astropy/coordinates/sky_coordinate.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,13 +194,12 @@ class or the corresponding string alias. The frame classes that are built in
# info property.
info = SkyCoordInfo()

def __init__(self, *args, **kwargs):
def __init__(self, *args, copy=True, **kwargs):

# Parse the args and kwargs to assemble a sanitized and validated
# kwargs dict for initializing attributes for this object and for
# creating the internal self._sky_coord_frame object
args = list(args) # Make it mutable
copy = kwargs.pop('copy', True)
kwargs = self._parse_inputs(args, kwargs)

frame = kwargs['frame']
Expand Down
4 changes: 2 additions & 2 deletions astropy/io/ascii/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,8 @@ def get_writer(Writer=None, fast_writer=True, **kwargs):
return writer


def write(table, output=None, format=None, Writer=None, fast_writer=True, **kwargs):
def write(table, output=None, format=None, Writer=None, fast_writer=True, *,
overwrite=None, **kwargs):
"""Write the input ``table`` to ``filename``. Most of the default behavior
for various parameters is determined by the Writer class.
Expand Down Expand Up @@ -693,7 +694,6 @@ def write(table, output=None, format=None, Writer=None, fast_writer=True, **kwar
Writer class (DEPRECATED).
"""
overwrite = kwargs.pop('overwrite', None)
if isinstance(output, str):
if os.path.lexists(output):
if overwrite is None:
Expand Down
23 changes: 6 additions & 17 deletions astropy/io/fits/convenience.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ def getheader(filename, *args, **kwargs):
return header


def getdata(filename, *args, **kwargs):
def getdata(filename, *args, header=None, lower=None, upper=None, view=None,
**kwargs):
"""
Get the data from an extension of a FITS file (and optionally the
header).
Expand Down Expand Up @@ -187,10 +188,6 @@ def getdata(filename, *args, **kwargs):
"""

mode, closed = _get_file_mode(filename)
header = kwargs.pop('header', None)
lower = kwargs.pop('lower', None)
upper = kwargs.pop('upper', None)
view = kwargs.pop('view', None)

hdulist, extidx = _getext(filename, mode, *args, **kwargs)
try:
Expand Down Expand Up @@ -271,7 +268,8 @@ def getval(filename, keyword, *args, **kwargs):
return hdr[keyword]


def setval(filename, keyword, *args, **kwargs):
def setval(filename, keyword, *args, value=None, comment=None, before=None,
after=None, savecomment=False, **kwargs):
"""
Set a keyword's value from a header in a FITS file.
Expand Down Expand Up @@ -330,12 +328,6 @@ def setval(filename, keyword, *args, **kwargs):
if 'do_not_scale_image_data' not in kwargs:
kwargs['do_not_scale_image_data'] = True

value = kwargs.pop('value', None)
comment = kwargs.pop('comment', None)
before = kwargs.pop('before', None)
after = kwargs.pop('after', None)
savecomment = kwargs.pop('savecomment', False)

closed = fileobj_closed(filename)
hdulist, extidx = _getext(filename, 'update', *args, **kwargs)
try:
Expand Down Expand Up @@ -948,18 +940,15 @@ def tableload(datafile, cdfile, hfile=None):
tableload.__doc__ += BinTableHDU._tdump_file_format.replace('\n', '\n ')


def _getext(filename, mode, *args, **kwargs):
def _getext(filename, mode, *args, ext=None, extname=None, extver=None,
**kwargs):
"""
Open the input file, return the `HDUList` and the extension.
This supports several different styles of extension selection. See the
:func:`getdata()` documentation for the different possibilities.
"""

ext = kwargs.pop('ext', None)
extname = kwargs.pop('extname', None)
extver = kwargs.pop('extver', None)

err_msg = ('Redundant/conflicting extension arguments(s): {}'.format(
{'args': args, 'ext': ext, 'extname': extname,
'extver': extver}))
Expand Down
8 changes: 2 additions & 6 deletions astropy/io/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,15 +478,13 @@ def get_writer(data_format, data_class):
data_format, data_class.__name__, format_table_str))


def read(cls, *args, **kwargs):
def read(cls, *args, format=None, **kwargs):
"""
Read in data.
The arguments passed to this method depend on the format.
"""

format = kwargs.pop('format', None)

ctx = None
try:
if format is None:
Expand Down Expand Up @@ -539,15 +537,13 @@ def read(cls, *args, **kwargs):
return data


def write(data, *args, **kwargs):
def write(data, *args, format=None, **kwargs):
"""
Write out data.
The arguments passed to this method depend on the format.
"""

format = kwargs.pop('format', None)

if format is None:
path = None
fileobj = None
Expand Down
18 changes: 7 additions & 11 deletions astropy/modeling/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -674,13 +674,11 @@ class Model(metaclass=_ModelMeta):
# inputs. Only has an effect if input_units is defined.
input_units_equivalencies = None

def __init__(self, *args, **kwargs):
def __init__(self, *args, meta=None, name=None, **kwargs):
super().__init__()
meta = kwargs.pop('meta', None)
if meta is not None:
self.meta = meta

self._name = kwargs.pop('name', None)
self._name = name

self._initialize_constraints(kwargs)
# Remaining keyword args are either parameter values or invalid
Expand Down Expand Up @@ -1406,7 +1404,8 @@ def return_units(self):
def return_units(self, return_units):
self._return_units = return_units

def prepare_inputs(self, *inputs, **kwargs):
def prepare_inputs(self, *inputs, model_set_axis=None, equivalencies=None,
**kwargs):
"""
This method is used in `~astropy.modeling.Model.__call__` to ensure
that all the inputs to the model can be broadcast into compatible
Expand All @@ -1417,9 +1416,8 @@ def prepare_inputs(self, *inputs, **kwargs):
"""

# When we instantiate the model class, we make sure that __call__ can
# take the following two keyword arguments.
model_set_axis = kwargs.pop('model_set_axis', None)
equivalencies = kwargs.pop('equivalencies', None)
# take the following two keyword arguments: model_set_axis and
# equivalencies.

if model_set_axis is None:
# By default the model_set_axis for the input is assumed to be the
Expand Down Expand Up @@ -2870,7 +2868,7 @@ def deepcopy(self):
return new_model


def custom_model(*args, **kwargs):
def custom_model(*args, fit_deriv=None):
"""
Create a model from a user defined function. The inputs and parameters of
the model will be inferred from the arguments of the function.
Expand Down Expand Up @@ -2939,8 +2937,6 @@ def custom_model(*args, **kwargs):
0.3333333333333333
"""

fit_deriv = kwargs.get('fit_deriv', None)

if len(args) == 1 and callable(args[0]):
return _custom_model_wrapper(args[0], fit_deriv=fit_deriv)
elif not args:
Expand Down
2 changes: 1 addition & 1 deletion astropy/modeling/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def model_a(x):
assert model_a.param_names == ()
assert model_a.n_inputs == 1
sig = signature(model_a.__init__)
assert list(sig.parameters.keys()) == ['self', 'args', 'kwargs']
assert list(sig.parameters.keys()) == ['self', 'args', 'meta', 'name', 'kwargs']
sig = signature(model_a.__call__)
assert list(sig.parameters.keys()) == ['self', 'x', 'model_set_axis',
'with_bounding_box', 'fill_value',
Expand Down
6 changes: 2 additions & 4 deletions astropy/nddata/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,10 @@ class NDDataArray(NDArithmeticMixin, NDSlicingMixin, NDIOMixin, NDData):
shape) onto ``data``.
"""

def __init__(self, data, *args, **kwd):
# Remove the flag argument from input.
flags = kwd.pop('flags', None)
def __init__(self, data, *args, flags=None, **kwargs):

# Initialize with the parent...
super().__init__(data, *args, **kwd)
super().__init__(data, *args, **kwargs)

# ...then reset uncertainty to force it to go through the
# setter logic below. In base NDData all that is done is to
Expand Down
6 changes: 2 additions & 4 deletions astropy/time/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -827,7 +827,7 @@ def replicate(self, format=None, copy=False):
"""
return self._apply('copy' if copy else 'replicate', format=format)

def _apply(self, method, *args, **kwargs):
def _apply(self, method, *args, format=None, **kwargs):
"""Create a new time object, possibly applying a method to the arrays.
Parameters
Expand Down Expand Up @@ -858,9 +858,7 @@ def _apply(self, method, *args, **kwargs):
index or slice : ``_apply('__getitem__', item)``
broadcast : ``_apply(np.broadcast, shape=new_shape)``
"""
new_format = kwargs.pop('format', None)
if new_format is None:
new_format = self.format
new_format = self.format if format is None else format

if callable(method):
apply_method = lambda array: method(array, *args, **kwargs)
Expand Down
3 changes: 1 addition & 2 deletions astropy/units/quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -1470,7 +1470,7 @@ def argmin(self, axis=None, out=None):
# the methods do not always allow calling with keyword arguments.
# For instance, np.array([0.,2.]).clip(a_min=0., a_max=1.) gives
# TypeError: 'a_max' is an invalid keyword argument for this function.
def _wrap_function(self, function, *args, **kwargs):
def _wrap_function(self, function, *args, out=None, **kwargs):
"""Wrap a numpy function that processes self, returning a Quantity.
Parameters
Expand Down Expand Up @@ -1501,7 +1501,6 @@ def _wrap_function(self, function, *args, **kwargs):
Result of the function call, with the unit set properly.
"""
unit = kwargs.pop('unit', self.unit)
out = kwargs.pop('out', None)
# Ensure we don't loop back by turning any Quantity into array views.
args = (self.value,) + tuple((arg.value if isinstance(arg, Quantity)
else arg) for arg in args)
Expand Down
4 changes: 1 addition & 3 deletions astropy/utils/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ def _write_with_fallback(s, write, fileobj):
return write


def color_print(*args, **kwargs):
def color_print(*args, end='\n', **kwargs):
"""
Prints colors and styles to the terminal uses ANSI escape
sequences.
Expand Down Expand Up @@ -354,8 +354,6 @@ def color_print(*args, **kwargs):

file = kwargs.get('file', _get_stdout())

end = kwargs.get('end', '\n')

write = file.write
if isatty(file) and conf.use_color:
for i in range(0, len(args), 2):
Expand Down
3 changes: 1 addition & 2 deletions astropy/visualization/wcsaxes/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ def get_tightbbox(self, renderer):
else:
return self.get_window_extent(renderer)

def grid(self, b=None, axis='both', **kwargs):
def grid(self, b=None, axis='both', *, which='major', **kwargs):
"""
Plot gridlines for both coordinates.
Expand All @@ -507,7 +507,6 @@ def grid(self, b=None, axis='both', **kwargs):
if not hasattr(self, 'coords'):
return

which = kwargs.pop('which', 'major')
if which != 'major':
raise NotImplementedError('Plotting the grid for the minor ticks is '
'not supported.')
Expand Down
36 changes: 17 additions & 19 deletions astropy/wcs/wcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,14 +187,21 @@ class NoConvergence(Exception):
"""

def __init__(self, *args, **kwargs):
def __init__(self, *args, best_solution=None, accuracy=None, niter=None,
divergent=None, slow_conv=None, **kwargs):
super().__init__(*args)

self.best_solution = kwargs.pop('best_solution', None)
self.accuracy = kwargs.pop('accuracy', None)
self.niter = kwargs.pop('niter', None)
self.divergent = kwargs.pop('divergent', None)
self.slow_conv = kwargs.pop('slow_conv', None)
self.best_solution = best_solution
self.accuracy = accuracy
self.niter = niter
self.divergent = divergent
self.slow_conv = slow_conv

if kwargs:
warnings.warn("Function received unexpected arguments ({}) these "
"are ignored but will raise an Exception in the "
"future.".format(list(kwargs)),
AstropyDeprecationWarning)


class FITSFixedWarning(AstropyWarning):
Expand Down Expand Up @@ -1198,15 +1205,11 @@ def _normalize_sky(self, sky):
out[:, 1] = sky[:, self.wcs.lat]
return out

def _array_converter(self, func, sky, *args, **kwargs):
def _array_converter(self, func, sky, *args, ra_dec_order=False):
"""
A helper function to support reading either a pair of arrays
or a single Nx2 array.
"""
ra_dec_order = kwargs.pop('ra_dec_order', False)
if len(kwargs):
raise TypeError("Unexpected keyword argument {0!r}".format(
kwargs.keys()[0]))

def _return_list_of_arrays(axes, origin):
try:
Expand Down Expand Up @@ -1810,21 +1813,16 @@ def _all_world2pix(self, world, origin, tolerance, maxiter, adaptive,

return pix

def all_world2pix(self, *args, **kwargs):
def all_world2pix(self, *args, tolerance=1e-4, maxiter=20, adaptive=False,
detect_divergence=True, quiet=False, **kwargs):
if self.wcs is None:
raise ValueError("No basic WCS settings were created.")

tolerance = kwargs.pop('tolerance', 1e-4)
maxiter = kwargs.pop('maxiter', 20)
adaptive = kwargs.pop('adaptive', False)
detect_div = kwargs.pop('detect_divergence', True)
quiet = kwargs.pop('quiet', False)

return self._array_converter(
lambda *args, **kwargs:
self._all_world2pix(
*args, tolerance=tolerance, maxiter=maxiter,
adaptive=adaptive, detect_divergence=detect_div,
adaptive=adaptive, detect_divergence=detect_divergence,
quiet=quiet),
'input', *args, **kwargs
)
Expand Down

0 comments on commit f9f5087

Please sign in to comment.