Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Last active August 5, 2024 17:58
Show Gist options
  • Save CodeByAidan/cd8bffdb34891d6216a7956d50165a40 to your computer and use it in GitHub Desktop.
Save CodeByAidan/cd8bffdb34891d6216a7956d50165a40 to your computer and use it in GitHub Desktop.
A test for special parameters in Python 3.12 + explanation for beginners
def baz(
a: int,
b: int,
/,
c: int | None = None,
*args: int,
d: int | None = None,
**kwargs: int,
) -> None:
print("--------------------")
print(f"a: {a}, b: {b}")
print(f"c: {c}")
print(f"args: {args}")
print(f"d: {d}")
print(f"kwargs: {kwargs}")
baz(1, 2) # Minimal call with position-only arguments
baz(1, 2, 3, 4, 5) # Adding more positional arguments
baz(1, 2, c=3, d=4, e=5) # Using keyword arguments for c, d, and an extra one
baz(1, 2, 3, 4, d=5, e=6) # Mixing positional and keyword arguments
--------------------
a: 1, b: 2
c: None
args: ()
d: None
kwargs: {}
--------------------
a: 1, b: 2
c: 3
args: (4, 5)
d: None
kwargs: {}
--------------------
a: 1, b: 2
c: 3
args: ()
d: 4
kwargs: {'e': 5}
--------------------
a: 1, b: 2
c: 3
args: (4,)
d: 5
kwargs: {'e': 6}
@CodeByAidan
Copy link
Author

Analysis:

  1. baz(1, 2)

    • Output:
      --------------------
      a: 1, b: 2
      c: None
      args: ()
      d: None
      kwargs: {}
      
    • Only the position-only arguments a and b are provided, with default values for the rest
  2. baz(1, 2, 3, 4, 5)

    • Output:
      --------------------
      a: 1, b: 2
      c: 3
      args: (4, 5)
      d: None
      kwargs: {}
      
    • c is specified by position, and args captures the additional positional arguments 4 and 5.
  3. baz(1, 2, c=3, d=4, e=5)

    • Output:
      --------------------
      a: 1, b: 2
      c: 3
      args: ()
      d: 4
      kwargs: {'e': 5}
      
    • c and d are specified by keyword, and e is stored in kwargs.
  4. baz(1, 2, 3, 4, d=5, e=6)

    • Output:
      --------------------
      a: 1, b: 2
      c: 3
      args: (4,)
      d: 5
      kwargs: {'e': 6}
      
    • c is specified by position, args captures 4, and d and e are in d and kwargs, respectively

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment