Skip to content

Commit 9295e10

Browse files
committed
Merge branch 'main' of github.com:PlasmaPy/PlasmaPy into enable-mypy
2 parents a3bcf0c + 0e87cbc commit 9295e10

5 files changed

Lines changed: 89 additions & 21 deletions

File tree

‎changelog/2428.feature.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Enabled |particle_input| to decorate functions which have variadic
2+
positional arguments followed by keyword arguments. See :issue:`2150`.

‎plasmapy/particles/decorators.py‎

Lines changed: 45 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import wrapt
1010

1111
from collections.abc import Iterable
12+
from inspect import BoundArguments
1213
from numbers import Integral, Real
1314
from typing import Any, Callable, NoReturn, Optional, Union
1415

@@ -69,20 +70,26 @@ def _make_into_set_or_none(obj) -> Optional[set]:
6970

7071

7172
def _bind_arguments(
73+
wrapped_signature: inspect.Signature,
7274
callable_: Callable,
7375
args: Optional[tuple] = None,
7476
kwargs: Optional[dict[str, Any]] = None,
7577
instance=None,
76-
) -> dict:
78+
) -> inspect.BoundArguments:
7779
"""
7880
Bind the arguments provided by ``args`` and ``kwargs`` to
7981
the corresponding parameters in the signature of the callable_
8082
or method being decorated.
8183
8284
Parameters
8385
----------
86+
wrapped_signature : `inspect.Signature`
87+
The signature of the function or method to which to bind
88+
``args`` and ``kwargs``.
89+
8490
callable_ : callable
8591
The function or method to which to bind ``args`` and ``kwargs``.
92+
This argument is only needed for a deprecation warning message.
8693
8794
args : tuple, optional
8895
Positional arguments.
@@ -101,7 +108,6 @@ def _bind_arguments(
101108
the corresponding arguments as values, but removing ``self`` and
102109
``cls``.
103110
"""
104-
wrapped_signature = inspect.signature(callable_)
105111

106112
# We should keep the warning about "z_mean" for perhaps ∼2
107113
# releases following the last pull request that removes a "z_mean"
@@ -134,12 +140,11 @@ def _bind_arguments(
134140
bound_arguments = wrapped_signature.bind(instance, *args, **kwargs)
135141

136142
bound_arguments.apply_defaults()
137-
arguments_to_be_processed = bound_arguments.arguments
138143

139-
arguments_to_be_processed.pop("self", None)
140-
arguments_to_be_processed.pop("cls", None)
144+
bound_arguments.arguments.pop("self", None)
145+
bound_arguments.arguments.pop("cls", None)
141146

142-
return arguments_to_be_processed
147+
return bound_arguments
143148

144149

145150
class _ParticleInput:
@@ -204,6 +209,12 @@ def callable_(self, callable_: Callable):
204209
self._data["callable"] = callable_
205210
self._data["annotations"] = _get_annotations(callable_)
206211
self._data["parameters_to_process"] = self.find_parameters_to_process()
212+
self._data["signature"] = inspect.signature(callable_)
213+
214+
@property
215+
def signature(self) -> inspect.Signature:
216+
"""The signature of the wrapped callable."""
217+
return self._data["signature"]
207218

208219
def find_parameters_to_process(self) -> list[str]:
209220
"""
@@ -553,9 +564,12 @@ def process_argument(
553564

554565
def perform_pre_validations(self, Z, mass_numb):
555566
"""
556-
Check that there are annotated parameters, that ``Z`` and
557-
``mass_numb`` are integers, and that ``Z`` and ``mass_numb`` are
558-
not parameters when more than one parameter is annotated.
567+
Perform a variety of pre-checks on the arguments.
568+
569+
Check that there are annotated parameters. Check that ``Z`` is
570+
a real number if not `None`. Check that ``mass_numb`` is an
571+
integer if not `None`. Verify that ``Z`` and ``mass_numb`` are
572+
not included if there are multiple annotated parameters.
559573
"""
560574

561575
if not self.parameters_to_process:
@@ -575,13 +589,13 @@ def perform_pre_validations(self, Z, mass_numb):
575589
if Z_or_mass_numb and multiple_annotated_parameters:
576590
raise ParticleError(
577591
"The arguments Z and mass_numb are not allowed when more "
578-
"than one argument or keyword is annotated with Particle "
579-
"in callables decorated with particle_input."
592+
"than one argument or keyword is annotated with ParticleLike "
593+
"in callables decorated with @particle_input."
580594
)
581595

582596
def process_arguments(
583597
self, args: tuple, kwargs: dict[str, Any], instance=None
584-
) -> dict[str, Any]:
598+
) -> BoundArguments:
585599
"""
586600
Process the arguments passed to the callable_ callable.
587601
@@ -597,20 +611,32 @@ def process_arguments(
597611
If the callable_ callable is a class instance method, then
598612
``instance`` should be the class instance to which ``func``
599613
belongs.
614+
615+
Notes
616+
-----
617+
This method does not work when there are positional arguments
618+
before variadic positional arguments. See :issue:`2150`.
600619
"""
601620

602-
arguments = _bind_arguments(self.callable_, args, kwargs, instance)
621+
bound_arguments = _bind_arguments(
622+
self.signature, self.callable_, args, kwargs, instance
623+
)
603624

604-
Z = arguments.pop("Z", None)
605-
mass_numb = arguments.pop("mass_numb", None)
625+
Z = bound_arguments.arguments.pop("Z", None)
626+
mass_numb = bound_arguments.arguments.pop("mass_numb", None)
606627

607628
self.perform_pre_validations(Z, mass_numb)
608629

609-
return {
630+
processed_kwargs = {
610631
parameter: self.process_argument(parameter, argument, Z, mass_numb)
611-
for parameter, argument in arguments.items()
632+
for parameter, argument in bound_arguments.arguments.items()
612633
}
613634

635+
for parameter in processed_kwargs:
636+
bound_arguments.arguments[parameter] = processed_kwargs[parameter]
637+
638+
return bound_arguments
639+
614640

615641
def particle_input(
616642
callable_: Optional[Callable] = None,
@@ -894,7 +920,7 @@ def instance_method(self, particle: ParticleLike, B: u.Quantity[u.T]):
894920
def wrapper(
895921
callable__: Callable, instance: Any, args: tuple, kwargs: dict[str, Any]
896922
):
897-
new_kwargs = particle_validator.process_arguments(args, kwargs, instance)
898-
return callable__(**new_kwargs)
923+
bound_arguments = particle_validator.process_arguments(args, kwargs, instance)
924+
return callable__(*bound_arguments.args, **bound_arguments.kwargs)
899925

900926
return wrapper(callable_)

‎plasmapy/particles/tests/test_decorators.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -654,3 +654,43 @@ def test_particle_input_warning_for_float_z_mean():
654654
Z = result.charge / const.e.si
655655

656656
assert u.isclose(Z, z_mean)
657+
658+
659+
def test_particle_input_with_var_positional_arguments():
660+
"""
661+
Test that |particle_input| works with functions that accept
662+
variadic positional arguments and keyword arguments.
663+
"""
664+
665+
@particle_input
666+
def function_with_var_positional_arguments(*args, particle: ParticleLike = None):
667+
return args, particle
668+
669+
args = (5, 6, 7)
670+
particle = "p+"
671+
expected = (args, Particle(particle))
672+
673+
actual = function_with_var_positional_arguments(*args, particle=particle)
674+
675+
assert actual == expected
676+
677+
678+
@pytest.mark.xfail(reason="See issue #2150.")
679+
def test_particle_input_with_pos_and_var_positional_arguments():
680+
"""
681+
Test that |particle_input| works with functions that accept
682+
positional followed by variadic positional arguments.
683+
"""
684+
685+
@particle_input
686+
def function_with_pos_and_var_positional_arguments(
687+
a, *args, particle: ParticleLike = None
688+
):
689+
return args, particle
690+
691+
a = 1
692+
args = (5, 6, 7)
693+
particle = "p+"
694+
expected = (a, args, Particle(particle))
695+
actual = function_with_pos_and_var_positional_arguments(a, *args, particle=particle)
696+
assert actual == expected

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ dependencies = [
5252
"requests >= 2.27.1",
5353
"scipy >= 1.7.0",
5454
"tqdm >= 4.60.0",
55-
"voila >= 0.3.3",
55+
"voila >= 0.5.0",
5656
"wrapt >= 1.12.1",
5757
"xarray >= 2022.3.0",
5858
]

‎tox.ini‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ deps =
135135
requests == 2.27.1
136136
scipy == 1.7.0
137137
tqdm == 4.60.0
138-
voila == 0.3.3
138+
voila == 0.5.0
139139
wrapt == 1.12.1
140140
xarray == 2022.3.0
141141
setenv =

0 commit comments

Comments
 (0)