Skip to content

Modernize test_inspect by adding real pos-only parameters #103406

Closed
@sobolevn

Description

@sobolevn

Right now test_inspect uses several hacks to pretend that some parameters are positional only:

def test(po, pk, pod=42, pkd=100, *args, ko, **kwargs):
pass
sig = inspect.signature(test)
po = sig.parameters['po'].replace(kind=P.POSITIONAL_ONLY)
pod = sig.parameters['pod'].replace(kind=P.POSITIONAL_ONLY)

myparam = MyParameter(name='z', kind=inspect.Parameter.POSITIONAL_ONLY)
myparams = collections.OrderedDict(sig.parameters, a=myparam)
mysig = MySignature().replace(parameters=myparams.values(),
return_annotation=sig.return_annotation)

def foo(a, b, c, d, **kwargs):
pass
sig = inspect.signature(foo)
params = sig.parameters.copy()
params['a'] = params['a'].replace(kind=Parameter.POSITIONAL_ONLY)
params['b'] = params['b'].replace(kind=Parameter.POSITIONAL_ONLY)

def test(a_po, *, b, **kwargs):
return a_po, kwargs
sig = inspect.signature(test)
new_params = list(sig.parameters.values())
new_params[0] = new_params[0].replace(kind=P.POSITIONAL_ONLY)
test.__signature__ = sig.replace(parameters=new_params)

def test(a_po, b_po, c_po=3, foo=42, *, bar=50, **kwargs):
return a_po, b_po, c_po, foo, bar, kwargs
sig = inspect.signature(test)
new_params = collections.OrderedDict(tuple(sig.parameters.items()))
for name in ('a_po', 'b_po', 'c_po'):
new_params[name] = new_params[name].replace(kind=P.POSITIONAL_ONLY)

And maybe others.

It makes code more complex, unclear, and hides the real purpose of these tests.

This is not a design decision, but rather a limitation at the time. Commits are quite old and pos-only syntax was not available 9 and 11 years ago:

So, I propose to simplify these tests and make them more correct by using explicit pos only parameters.

Plus, we can keep one test like this to be sure that chaning a parameter kind still works as before. But, there's no need in keeping these old tests the way they are.

I will send a PR with the fix 👍

Linked PRs

Metadata

Metadata

Assignees

Labels

testsTests in the Lib/test dirtype-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions