Python __kwdefaults__

The __kwdefaults__ attribute in Python is used to retrieve the default values for keyword arguments in a function or method. It provides a dictionary that maps the names of the keyword arguments to their default values.

Example:


  def greet(name, message="Hello"):
      print(f"{message}, {name}!")
      
  print(greet.__kwdefaults__)
  

In the above example, the function greet has a keyword argument message with a default value of "Hello". By accessing the __kwdefaults__ attribute of the function, we can retrieve the default value as a dictionary:

{'message': 'Hello'}

This shows that the default value for the message keyword argument is "Hello".

It is important to note that the __kwdefaults__ attribute is only available for functions or methods that have keyword arguments with default values. Functions without any keyword arguments or without default values will not have this attribute.

Leave a comment