[Python]#14 Order of Function Arguments

Jude's Sound Lab·2025년 1월 22일

Algorithm & Coding

목록 보기
4/5

The Correct Order of Function Arguments

1. Positional-only arguments (/):

These arguments can only be passed positionally (no keywords allowed).
Introduced in Python 3.8 using /.

2. Positional and keyword arguments:

Regular arguments that can be passed either positionally or by keyword.
This includes *args, which captures any additional positional arguments into a tuple.

3. Keyword-only arguments:

These arguments must be passed as keywords.
To define these, use * or *args to "block" further positional arguments.

4. Arbitrary keyword arguments (**kwargs):

Captures additional keyword arguments into a dictionary.

Example

  1. Positional-only Arguments
    These can only be passed positionally (not by keyword). To define them, use /.
def greet(name, /):
    print(f"Hello, {name}!")

# Valid calls
greet("Alice")

# Invalid call
greet(name="Alice")  # Raises TypeError
  1. Positional and Keyword Arguments
    These arguments can be passed either positionally or by keyword.
def greet(name, age):
    print(f"{name} is {age} years old.")

# Valid calls
greet("Alice", 25)          # Positional
greet(name="Alice", age=25) # Keyword
greet("Alice", age=25)      # Mixed
  1. Keyword-only Arguments
    These arguments must be passed as keywords. To define them:

Use * if you don't have *args.
If you do have *args, the arguments after *args are automatically keyword-only.

def greet(name, *, age):
    print(f"{name} is {age} years old.")

# Valid call
greet("Alice", age=25)  # Keyword argument for `age`

# Invalid call
greet("Alice", 25)  # Raises TypeError

# With *args
def greet(name, *args, age):
    print(f"{name}, {args}, is {age} years old.")

greet("Alice", "Student", "Musician", age=25)
# Output: Alice, ('Student', 'Musician'), is 25 years old.
  1. Arbitrary Keyword Arguments
    Use **kwargs to collect additional keyword arguments into a dictionary.
def greet(name, **kwargs):
    print(f"Hello, {name}!")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Example usage
greet("Alice", age=25, city="Seoul", hobby="Music")

# Output:
# Hello, Alice!
# age: 25
# city: Seoul
# hobby: Music
profile
chords & code // harmony with structure

0개의 댓글