Skip to content

Commit da0615f

Browse files
committed
Ignore the "self" argument for methods in posargs2kwargs
1 parent 7eabbf5 commit da0615f

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

domdf_python_tools/utils.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
from io import StringIO
7070
from math import log10
7171
from pprint import pformat
72+
from types import MethodType
7273
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Pattern, Tuple, Union
7374

7475
# this package
@@ -249,16 +250,29 @@ def posargs2kwargs(
249250
:default kwargs: ``{}``
250251
251252
:return: Dictionary mapping argument names to values.
253+
254+
.. versionchanged:: 2.8.0
255+
256+
The "self" argument for bound methods is ignored.
257+
For unbound methods (which are just functions) the behaviour is unchanged.
252258
"""
253259

254260
if kwargs is None:
255261
kwargs = {}
256262

257-
if callable(posarg_names):
263+
self_arg = None
264+
265+
if isinstance(posarg_names, MethodType):
266+
posarg_names = inspect.getfullargspec(posarg_names).args
267+
self_arg = posarg_names[0]
268+
elif callable(posarg_names):
258269
posarg_names = inspect.getfullargspec(posarg_names).args
259270

260271
kwargs.update(zip(posarg_names, args))
261272

273+
if self_arg is not None and self_arg in kwargs:
274+
del kwargs[self_arg]
275+
262276
# TODO: positional only arguments
263277

264278
return kwargs

tests/test_utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,9 @@ def demo_function(arg1, arg2, arg3):
264264
pass
265265

266266

267+
cwd = pathlib.Path.cwd()
268+
269+
267270
@pytest.mark.parametrize(
268271
"args, posarg_names, kwargs, expects",
269272
[
@@ -275,6 +278,21 @@ def demo_function(arg1, arg2, arg3):
275278
"arg2": 2,
276279
"arg3": 3,
277280
}),
281+
((cwd, "wb", -1, "UTF-8"),
282+
pathlib.Path.open,
283+
None, {
284+
"self": cwd,
285+
"mode": "wb",
286+
"buffering": -1,
287+
"encoding": "UTF-8",
288+
}),
289+
((cwd, "wb", -1, "UTF-8"),
290+
pathlib.Path().open,
291+
None, {
292+
"mode": "wb",
293+
"buffering": -1,
294+
"encoding": "UTF-8",
295+
}),
278296
]
279297
)
280298
def test_posargs2kwargs(args, posarg_names, kwargs, expects):

0 commit comments

Comments
 (0)