Types of arguments#
Python gives you flexible ways to pass values into functions:
- Positional arguments
- Keyword arguments
- Default parameter values
- Variable-length
*args - Variable-length keyword
**kwargs
1. Positional arguments#
Values are matched to parameters by position (order):
2. Keyword arguments#
Name the parameter in the call - then order doesn't matter, and the call is easier to read:
Positional arguments must come before keyword arguments in a call: introduce(name="Neha", 19, "Ujjain") is a SyntaxError.
3. Default parameter values#
Give a parameter a default; the caller may skip it:
Parameters with defaults must come after those without:
def f(a=1, b): # SyntaxError: non-default argument follows default argument
The mutable default trap#
Never use a list or dict as a default value. The default is created once, when the function is defined, and shared between calls:
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("pen")) # ['pen']
print(add_item("book")) # ['pen', 'book'] <- surprise!
Use None instead:
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
4. *args - any number of positional arguments#
A parameter starting with * collects all extra positional arguments into a tuple:
The name args is just a convention - *marks or *numbers work the same. The * is what matters.
5. **kwargs - any number of keyword arguments#
A parameter starting with ** collects extra keyword arguments into a dictionary:
*args और **kwargs तब काम आते हैं जब आपको पहले से पता न हो कि function को कितनी values मिलेंगी:
*args(एक star) - बिना नाम वाली सारी extra values को एक tuple में इकट्ठा कर देता है। जैसेaverage(80, 90, 70)→marks = (80, 90, 70)**kwargs(दो star) - नाम वाली (key=value) सारी extra values को एक dictionary में इकट्ठा कर देता है। जैसेprint_details(name="Ravi", city="Indore")→{'name': 'Ravi', 'city': 'Indore'}
args और kwargs सिर्फ परंपरागत नाम हैं - असली काम * और ** करते हैं।
Combining everything#
The order of parameters in a definition must be:
def func(positional, default=value, *args, keyword_only, **kwargs):
Parameters after *args (like delivery above) can only be passed by keyword.
Unpacking arguments in a call#
* and ** also work the other way - spreading a list or dict into separate arguments:
Summary#
- Positional arguments match by order; keyword arguments match by name.
- Default values make parameters optional - put them after required ones.
- Don't use mutable defaults (
[],{}); useNoneand create inside. *args→ tuple of extra positional values;**kwargs→ dict of extra keyword values.- In calls,
*listand**dictunpack values into arguments.