You can in modern Python (3, that is):

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "<ipython-input-5-08a2da4138f6>", line 1, in <module>
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "<ipython-input-7-14386ea74437>", line 1, in <module>
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob
Answer from DSM on Stack Overflow
🌐
UC Berkeley Statistics
stat.berkeley.edu › ~spector › extension › python › notes › node66.html
Named Arguments and Default Values
When you call a function, you can precede some or all of the arguments by a name and an equal sign, to let the function know exactly which argument you are passing to the function. So if we invoke the count_letter function as · num = count_letter(letter='a',string='dead parrot') we will get the correct answer (2) even though the arguments are in a different order than they were defined. To provide even greater flexibility, when you define a function Python allows you to specify a default value for any or all of the arguments to that function; the user then need only supply those arguments for which there are no defaults, and specifying the arguments with defaults in the function definition becomes optional.
🌐
Python
peps.python.org › pep-3102
PEP 3102 – Keyword-Only Arguments | peps.python.org
This function accepts any number ... positional argument, but must be explicitly specified by name. Keyword-only arguments are not required to have a default value....
Discussions

python - Can you have keyword arguments without supplying a default value? - Stack Overflow
Its Python 2.7 I am using. 2015-04-19T14:22:35.67Z+00:00 ... Likewise, if you want to specify positional arguments and accept more keyword arguments, you can write: def func(*args, name1, name2, **kwargs). 2018-10-06T21:38:10.51Z+00:00 ... Because of what says tdelaney, I think the solution given by Dolda2000 is relevant i.e. "Any argument can be given as with a keyword expression, whether or not it has a default... More on stackoverflow.com
🌐 stackoverflow.com
python - Named parameter with no default? - Stack Overflow
Don't use defaults if the parameters are not optional. You can still use those parameters as named parameters in the call; all parameters in a Python function are named: More on stackoverflow.com
🌐 stackoverflow.com
python - Normal arguments vs. keyword arguments - Stack Overflow
And whether or not there is a default value has nothing to do with it (except whether or not you need pass a value for it), right? ... I can't add Python-3.0 myself here. peps.python.org/pep-0000 ... There are two related concepts, both called "keyword arguments". On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without ... More on stackoverflow.com
🌐 stackoverflow.com
python - Get a function argument's default value? - Stack Overflow
Args with default values cannot be interspersed with args without default values, so mapping the default values to the args list, starting at the last argument and moving backwards, correctly connects the two. 2012-09-27T18:02:33.14Z+00:00 ... To those looking for a version to grab a specific default parameter with mgilson's answer. value = signature(my_func).parameters['param_name'].default · Here's a full working version, done in Python ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Linux Manual Page
linux.die.net › diveintopython › html › power_of_introspection › optional_arguments.html
4.2. Using Optional and Named Arguments
Python allows function arguments to have default values; if the function is called without the argument, the argument gets its default value. Futhermore, arguments can be specified in any order by using named arguments.
🌐
Learn Python
learnpython.dev › 02-introduction-to-python › 060-functions › 30-function-arguments
Function Arguments :: Learn Python by Nina Zakharenko
Functions can accept two types of named arguments, ones without default values, and ones with default values. Arguments that have default values are called keyword arguments.
🌐
Programiz
programiz.com › python-programming › function-argument
Python Function Arguments (With Examples)
Similarly, last_name in the function ... number of arguments that will be passed into a function. To handle this kind of situation, we can use arbitrary arguments in Python....
Find elsewhere
Top answer
1 of 10
418

There are two related concepts, both called "keyword arguments".

On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.

The other concept is on the function definition side: you can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is

def my_function(arg1, arg2, **kwargs)

Any keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this:

def my_function(**kwargs):
    print str(kwargs)

my_function(a=12, b="abc")

{'a': 12, 'b': 'abc'}
2 of 10
224

There is one last language feature where the distinction is important. Consider the following function:

def foo(*positional, **keywords):
    print "Positional:", positional
    print "Keywords:", keywords

The *positional argument will store all of the positional arguments passed to foo(), with no limit to how many you can provide.

>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}

The **keywords argument will store any keyword arguments:

>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}

And of course, you can use both at the same time:

>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}

These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.

🌐
Real Python
realpython.com › python-optional-arguments
Using Python Optional Arguments When Defining Functions – Real Python
October 27, 2025 - The parameters with no default value must always come before those that have a default value. Note: Since Python 3.8, you can also mark positional-only parameters with a forward slash (/) and keyword-only parameters with an asterisk (*). Read ...
🌐
Trey Hunner
treyhunner.com › 2018 › 04 › keyword-arguments-in-python
Keyword (Named) Arguments in Python: How to Use Them
That joiner variable doesn’t have a default value, so it must be specified: Note that this syntax of putting arguments after the * only works in Python 3. There’s no syntactic way in Python 2 to require an argument to be named. What if you want to accept keyword-only arguments without also ...
🌐
Hexlet
hexlet.io › courses › python-functions › lessons › keyword-arguments › theory_unit
Named arguments | Python: Functions - Hexlet
We should specify positional values before any named ones. Otherwise, you will get SyntaxError: positional argument follows keyword argument. Also, when a function has positional arguments without default values, the values for these arguments must be specified one way or another, either as ...
Top answer
1 of 8
175

Python3.x

In a python3.x world, you should probably use a Signature object:

import inspect

def get_default_args(func):
    signature = inspect.signature(func)
    return {
        k: v.default
        for k, v in signature.parameters.items()
        if v.default is not inspect.Parameter.empty
    }

Python2.x (old answer)

The args/defaults can be combined as:

import inspect
a = inspect.getargspec(eat_dog)
zip(a.args[-len(a.defaults):],a.defaults)

Here a.args[-len(a.defaults):] are the arguments with defaults values and obviously a.defaults are the corresponding default values.

You could even pass the output of zip to the dict constructor and create a mapping suitable for keyword unpacking.


looking at the docs, this solution will only work on python2.6 or newer since I assume that inspect.getargspec returns a named tuple. Earlier versions returned a regular tuple, but it would be very easy to modify accordingly. Here's a version which works with older (and newer) versions:

import inspect
def get_default_args(func):
    """
    returns a dictionary of arg_name:default_values for the input function
    """
    args, varargs, keywords, defaults = inspect.getargspec(func)
    return dict(zip(args[-len(defaults):], defaults))

Come to think of it:

    return dict(zip(reversed(args), reversed(defaults)))

would also work and may be more intuitive to some people.


2 of 8
17

To those looking for a version to grab a specific default parameter with mgilson's answer.

value = signature(my_func).parameters['param_name'].default

Here's a full working version, done in Python 3.8.2

from inspect import signature

def my_func(a, b, c, param_name='apple'):
    pass

value = signature(my_func).parameters['param_name'].default

print(value == 'apple') # True
Top answer
1 of 3
4

Just call that functions as

foo(a=3, c=10)

Alternatively, you could use the following approach, which is e.g. necessary for lists, because default values are evaluated in the module scope:

def foo(a=None, b=None, c=None):
    local_a = a or "default"
    ...

foo(a=42, b=None, c=16)

None then encodes to use the default, if None is no valid option.

Finally, you could just defined the defaults as "constants":

DEFAULT_A = 42
DEFAULT_B = "foo"
DEFAULT_C = 17

def foo(a=DEFAULT_A, b=DEFAULT_B, c=DEFAULT_C):
    pass

foo(16, DEFAULT_B, 123)

But this is quite uncommon.

For you updated example, I would propose to use * and ** operators:

def create_foo(*args, **kwargs):
    f = foo(*args, **kwargs)

create_foo(42, b="non-default")

See this question for explanations how these operators work.

2 of 3
2

If you don't use *args and **kwargs and subclassing there is no reason to explicitly call the defaults and as long as you are using only your own classes and you don't need mutual default arguments, you can just hand over the same values as the defaults - BUT if you are working with *args and **kwargs and the method to be called is from a super class, you might get problems with the MRO. (See this article for further information: https://www.python.org/download/releases/2.3/mro/)

The only way I know to prevent a(n at this moment unknown) super class to pass an argument to the class your calss extends is to call the method explicidly and than hand over only the arguments you want it to get.
I don't see another use case for an explicit default call.

🌐
Codecademy
codecademy.com › learn › learn-intermediate-python-3 › modules › int-python-function-arguments › cheatsheet
Learn Intermediate Python 3: Function Arguments Cheatsheet | Codecademy
Python functions can be defined with named arguments which may have default values provided. When function arguments are passed using their names, they are referred to as keyword arguments.
🌐
The Hitchhiker's Guide to Python
docs.python-guide.org › writing › gotchas
Common Gotchas — The Hitchhiker's Guide to Python
A new list is created each time the function is called if a second argument isn’t provided, so that the output is: ... A new list is created once when the function is defined, and the same list is used in each successive call. Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby).
Top answer
1 of 2
7

Mixing parameters with and without default values can indeed be confusing. Parameters are the names used in the function definition, arguments are the values passed into a call.

When calling, Python will always fill all parameters from positional arguments, including names with default values. size is just another parameter here, even though it has a default value. You can also use name=value syntax in a call to assign an argument value to a specific parameter (whether or not they have a default value). But you can't tell Python not to assign something to size, not with your current function definition, because everything before the *toppings parameter is always going to be a regular positional parameter.

The *toppings parameter will only capture any positional arguments after all the other parameters have received values. So 'onion' is assigned to size, and the remainder is assigned to *toppings.

In Python 3, you can make size a keyword-only parameter, by placing them as name=default after the *toppings name, or an empty *:

def make_pizza(*toppings, size=15):

Now size can only be set from a call with size=<new value> keyword argument syntax.

In Python 2, you can only capture such keyword arguments with a **kwargs catch-all parameter, after which you need to look into that dictionary for your size:

def make_pizza(*toppings, **kwargs):
    size = kwargs.get('size', 15)  # set a default if missing

In both cases, you have to remember to explicitly name size, and put such explicitly named keyword arguments after the positional arguments:

make_pizza('ham', 'extra meat', 'sweet con', 'pepperoni', size=17)
2 of 2
3

There's a fundamental problem with your approach: It's ambiguous because how do you know if you intended it as size or as topping? Python can't do that so you need to find an alternative.

Well, you could simply remove size from the argument list and interpret the first *toppings argument as size if it's an integer:

def make_pizza(*toppings):
    if toppings and isinstance(toppings[0], int):
        size, toppings = toppings[0], toppings[1:]
    else:
        size = 15
    print("\nMaking a {}-inch pizza with the following toppings: ".format(size))
    for topping in toppings:
        print("- " + topping)

However that will fail for cases where a simple type check isn't possible. Maybe the better approach would be to make toppings a normal argument and size an optional argument:

def make_pizza(toppings, size=15):
    print("\nMaking a {}-inch pizza with the following toppings: ".format(size))
    for topping in toppings:
        print("- " + topping)

However then you need to pass in a sequence for toppings and it changes the order of toppings and size but it's probably a lot cleaner.

make_pizza(['onion','shrimp','goda cheese','mushroom'])
make_pizza(['ham','extra meat','sweet con','pepperoni'], 17)

You could also keep the toppings as arbitary positional arguments and make size a keyword-only parameter with default (Python3-only):

def make_pizza(*toppings, size=15):
    print("\nMaking a {}-inch pizza with the following toppings: ".format(size))
    for topping in toppings:
        print("- " + topping)

make_pizza('onion','shrimp','goda cheese','mushroom')
make_pizza('ham','extra meat','sweet con','pepperoni', size=17)
🌐
Readthedocs
python-3-for-scientists.readthedocs.io › en › latest › python3_advanced.html
Useful Python 3 features (advanced) — Python 3 guide for scientists documentation
Now that we know the difference between positional arguments and keyword arguments, we can introduce keyword-only arguments. These are only specifiable via the name of the argument, and cannot be specified as a positional argument.
🌐
Reddit
reddit.com › r/python › today i re-learned: python function default arguments are retained between executions
r/Python on Reddit: Today I re-learned: Python function default arguments are retained between executions
January 20, 2023 - The mechanics of passed arguments is consistent regardless of type or mutability when you understand that arguments are just assigned to their corresponding parameters… due to the fact that Python doesn’t really have “variables” and only has “names” that point to “values,” the apparent effects of that do seem to vary depending on type behavior.
🌐
GeeksforGeeks
geeksforgeeks.org › python › default-arguments-in-python
Default arguments in Python - GeeksforGeeks
Non-default parameters must come before default parameters in the function definition. Positional arguments must come before keyword arguments when calling a function. If using keyword arguments, order does not matter.
Published   1 month ago
🌐
Python Discord
pythondiscord.com › pages › guides › python-guides › parameters-and-arguments
Python Discord | Function Parameters and Arguments in Python
You must specify any parameters without a default value before those with default values: def foo(a=0, b): ^ SyntaxError: non-default argument follows default argument · Python 3.8 / PEP 570 introduces the possibility to specify which parameters are required to be positional-only via a bare ...