2
def foo(a=MyComplexObject(), b=Something(), *args):
    print a, b, args

Is there a way to call foo with specifying *args and not specifying a or b in the function call - thus using there default values?

Something like

foo(*args=(1,2,3))

This is purely out of curiosity.

1
  • IIRC, in this example a & b are only instantiated once,so it's the same as default_a = MyComplexObject() , def foo(a=default_a):; args come before kwargs in python 2.7 too. Commented Mar 21, 2013 at 15:29

1 Answer 1

3

You'll have to move your keyword arguments to a variable keyword capture too:

def foo(*args, **kw):
    a = kw.get('a', MyComplexObject())
    b = kw.get('b', b=Something())
    print a, b, args

Python will fill the two keyword arguments first otherwise, as in Python 2 there is no way to specify that these keywords cannot be filled by positional arguments.

Python 3 changed the interpretation of the positional catchall parameter to make this possible without forcing you to use the ** keyword parameter catch-all.

If you cannot change the function definition yourself or upgrade to Python 3, then your only recourse is to specify the defaults again, or retrieve them from the function (using the inspect.getargspec() convenience function):

import inspect

defaults = inspect.getargspec(foo).defaults
foo(*(defaults + (1,2,3)))

defaults here is a tuple of the keyword argument default values.

Demonstration:

>>> import inspect
>>> def foo(a='spam', b='foo', *args):
...     print a, b, args
... 
>>> defaults = inspect.getargspec(foo).defaults
>>> foo(*(defaults + (1,2,3)))
spam foo (1, 2, 3)
Sign up to request clarification or add additional context in comments.

4 Comments

Does not answer my question. I can not change the function signature or what is inside of the function.
@mkorpela: That is how you'll have to do it to make this work.
@mkorpela then you have to do: `foo(MyComplexObject(), Something(), *(1, 2, 3))
I haven't got access to the default values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.