dimanche 8 septembre 2019

Python `inspect.Signature` shows all defined positional arguments as `ParameterKind.POSITIONAL_OR_KEYWORD`

I had the impression that you could use the inspect.Signature function to retrieve and distinguish between positional and keyword arguments. However this does not seem to be the case:

def foo(a,b,c, t=3, q=5):
    print(a,b,c,t,q)

[(u, u.kind) for u in i.signature(foo).parameters.values()]

[(<Parameter "a">, <_ParameterKind.POSITIONAL_OR_KEYWORD: 1>),
 (<Parameter "b">, <_ParameterKind.POSITIONAL_OR_KEYWORD: 1>),
 (<Parameter "c">, <_ParameterKind.POSITIONAL_OR_KEYWORD: 1>),
 (<Parameter "t=3">, <_ParameterKind.POSITIONAL_OR_KEYWORD: 1>),
 (<Parameter "q=5">, <_ParameterKind.POSITIONAL_OR_KEYWORD: 1>)]


So, as it is, seems the kind attribute is pretty useless to distinguish between positional and keyword arguments

So the question here is:

How do I distinguish between arguments a,b,c and arguments t,q so that if I were to invoke foo:

  #build args from signature with args = [a,b,c]
  #build kwargs from signature with kwargs = {'t': t,'q': q}
  foo(*args, **kwargs)





Aucun commentaire:

Enregistrer un commentaire