Skip to content

Commit

Permalink
Enable ruff D401
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcSkovMadsen committed Dec 25, 2024
1 parent f7d679d commit 7843a0a
Show file tree
Hide file tree
Showing 11 changed files with 364 additions and 131 deletions.
42 changes: 27 additions & 15 deletions numbergen/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,20 @@ class BinaryOperator(NumberGenerator):
"""Applies any binary operator to NumberGenerators or numbers to yield a NumberGenerator."""

def __init__(self,lhs,rhs,operator,reverse=False,**args):
"""Initialize a BinaryOperator with operands, an operator, and optional arguments.
Args:
lhs: The left-hand side operand, which can be a NumberGenerator or a number.
rhs: The right-hand side operand, which can be a NumberGenerator or a number.
operator (Callable): The binary operator to apply to the operands.
reverse (bool, optional): If `True`, swaps the left and right operands. Defaults to `False`.
**args: Optional keyword arguments to pass to the operator when it is called.
Notes
-----
It is currently not possible to set parameters in the superclass during
initialization because `**args` is used by this class itself.
"""
Accepts two NumberGenerator operands, an operator, and
optional arguments to be provided to the operator when calling
it on the two operands.
"""
# Note that it's currently not possible to set
# parameters in the superclass when creating an instance,
# because **args is used by this class itself.
super().__init__()

if reverse:
Expand All @@ -174,14 +180,18 @@ class UnaryOperator(NumberGenerator):
"""Applies any unary operator to a NumberGenerator to yield another NumberGenerator."""

def __init__(self,operand,operator,**args):
"""Initialize a UnaryOperator with an operand, operator, and optional arguments.
Args:
operand (NumberGenerator): The NumberGenerator to which the operator is applied.
operator (Callable): The unary operator to apply to the operand.
**args: Optional keyword arguments to pass to the operator when it is called.
Notes
-----
It is currently not possible to set parameters in the superclass during
initialization because `**args` is used by this class itself.
"""
Accepts a NumberGenerator operand, an operator, and
optional arguments to be provided to the operator when calling
it on the operand.
"""
# Note that it's currently not possible to set
# parameters in the superclass when creating an instance,
# because **args is used by this class itself.
super().__init__()

self.operand=operand
Expand Down Expand Up @@ -330,7 +340,9 @@ class TimeAwareRandomState(TimeAware):

def _initialize_random_state(self, seed=None, shared=True, name=None):
"""
Initialization method to be called in the constructor of
Initialize the random state correctly.
Method to be called in the constructor of
subclasses to initialize the random state correctly.
If seed is None, there is no control over the random stream
Expand Down
105 changes: 79 additions & 26 deletions param/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,19 @@ class Skip(Exception):

def _deprecated(extra_msg="", warning_cat=ParamDeprecationWarning):
def decorator(func):
"""Internal decorator used to mark functions/methods as deprecated."""
"""Mark a function or method as deprecated.
This internal decorator issues a warning when the decorated function
or method is called, indicating that it has been deprecated and will
be removed in a future version.
Args:
func: The function or method to mark as deprecated.
Returns
-------
Callable: The wrapped function that issues a deprecation warning.
"""
@functools.wraps(func)
def inner(*args, **kwargs):
msg = f"{func.__name__!r} has been deprecated and will be removed in a future version."
Expand All @@ -81,11 +93,19 @@ def inner(*args, **kwargs):


def _deprecate_positional_args(func):
"""
Internal decorator for methods that issues warnings for positional arguments
Using the keyword-only argument syntax in pep 3102, arguments after the
``*`` will issue a warning when passed as a positional argument.
Adapted from scikit-learn.
"""Issue warnings for methods using deprecated positional arguments.
This internal decorator warns when arguments after the `*` separator
are passed as positional arguments, in accordance with PEP 3102.
It adapts the behavior from scikit-learn.
Args:
func: The function to wrap with positional argument deprecation warnings.
Returns
-------
Callable: The wrapped function that issues warnings for deprecated
positional arguments.
"""
signature = inspect.signature(func)

Expand Down Expand Up @@ -124,7 +144,7 @@ def inner(*args, **kwargs):

# Copy of Python 3.2 reprlib's recursive_repr but allowing extra arguments
def _recursive_repr(fillvalue='...'):
"""Decorator to make a repr function return fillvalue for a recursive call."""
"""Decorate a repr function to return a fill value for recursive calls."""

def decorating_function(user_function):
repr_running = set()
Expand Down Expand Up @@ -201,7 +221,10 @@ def _validate_error_prefix(parameter, attribute=None):


def _is_mutable_container(value):
"""True for mutable containers, which typically need special handling when being copied."""
"""Determine if the value is a mutable container.
Mutable containers typically require special handling when being copied.
"""
return isinstance(value, MUTABLE_TYPES)


Expand Down Expand Up @@ -281,18 +304,17 @@ def flatten(line):
def accept_arguments(
f: Callable[Concatenate[CallableT, P], R]
) -> Callable[P, Callable[[CallableT], R]]:
"""Decorator for decorators that accept arguments."""
"""Decorate a decorator to accept arguments."""
@functools.wraps(f)
def _f(*args: P.args, **kwargs: P.kwargs) -> Callable[[CallableT], R]:
return lambda actual_f: f(actual_f, *args, **kwargs)
return _f


def _produce_value(value_obj):
"""
A helper function that produces an actual parameter from a stored
object: if the object is callable, call it, otherwise return the
object.
"""Produce an actual value from a stored object.
If the object is callable, call it; otherwise, return the object.
"""
if callable(value_obj):
return value_obj()
Expand All @@ -303,10 +325,9 @@ def _produce_value(value_obj):
# PARAM3_DEPRECATION
@_deprecated(warning_cat=ParamFutureWarning)
def produce_value(value_obj):
"""
A helper function that produces an actual parameter from a stored
object: if the object is callable, call it, otherwise return the
object.
"""Produce an actual value from a stored object.
If the object is callable, call it; otherwise, return the object.
.. deprecated:: 2.0.0
"""
Expand Down Expand Up @@ -556,9 +577,18 @@ def abbreviate_paths(pathspec,named_paths):


def _to_datetime(x):
"""
Internal function that will convert date objs to datetime objs, used
for comparing date and datetime objects without error.
"""Convert a date object to a datetime object for comparison.
This internal function ensures that date and datetime objects can be
compared without errors by converting date objects to datetime objects.
Args:
x: The object to convert, which may be a `date` or `datetime` object.
Returns
-------
datetime.datetime: A datetime object if the input was a date object;
otherwise, the input is returned unchanged.
"""
if isinstance(x, dt.date) and not isinstance(x, dt.datetime):
return dt.datetime(*x.timetuple()[:6])
Expand All @@ -567,9 +597,19 @@ def _to_datetime(x):

@contextmanager
def exceptions_summarized():
"""
Useful utility for writing docs that need to show expected errors.
Shows exception only, concisely, without a traceback.
"""Context manager to display exceptions concisely without tracebacks.
This utility is useful for writing documentation or examples where
only the exception type and message are needed, without the full
traceback.
Yields
------
None: Allows the code inside the context to execute.
Prints:
A concise summary of any exception raised, including the exception
type and message, to `sys.stderr`.
"""
try:
yield
Expand Down Expand Up @@ -616,9 +656,22 @@ def __iter__(cls):
yield from cls.types()

def gen_types(gen_func):
"""
Decorator which takes a generator function which yields difference types
make it so it can be called with isinstance and issubclass.
"""Decorate a generator function to support type checking.
This decorator modifies a generator function that yields different types
so that it can be used with `isinstance` and `issubclass`.
Args:
gen_func (function): The generator function to decorate.
Returns
-------
type: A new type that supports `isinstance` and `issubclass` checks
based on the generator function's yielded types.
Raises
------
TypeError: If the provided function is not a generator function.
"""
if not inspect.isgeneratorfunction(gen_func):
msg = "gen_types decorator can only be applied to generator"
Expand Down
25 changes: 18 additions & 7 deletions param/ipython.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def _build_table(self, info, order, max_col_len=40, only_changed=False):

def _tabulate(self, info_list, col_widths, changed, order, bounds_dict):
"""
Returns the supplied information as a table suitable for
Return the supplied information as a table suitable for
printing or paging.
info_list: List of the parameters name, type and mode.
Expand Down Expand Up @@ -320,13 +320,24 @@ def __init__(self, *args, **kwargs):

@line_magic
def params(self, parameter_s='', namespaces=None):
"""
The %params line magic accepts a single argument which is a
handle on the parameterized object to be inspected. If the
object can be found in the active namespace, information about
the object's parameters is displayed in the IPython pager.
"""Display information about a parameterized object in the IPython pager.
The `%params` line magic takes a single argument, which is a reference to
a parameterized object or class to be inspected. If the object is found in
the active namespace, information about its parameters is displayed in the
IPython pager.
Usage:
%params <parameterized class or object>
Args:
parameter_s (str, optional): The name of the parameterized object to inspect.
Defaults to an empty string.
namespaces (optional): Additional namespaces to search for the object.
Usage: %params <parameterized class or object>
Returns
-------
None: Outputs the parameter information or error messages directly.
"""
if parameter_s=='':
print("Please specify an object to inspect.")
Expand Down
Loading

0 comments on commit 7843a0a

Please sign in to comment.