Python functions for Java developers: default and keyword arguments

Python has no method overloading and almost no builders, and it doesn't miss them. Default values and keyword arguments do the same job in one function. Here is how def, *args, **kwargs and lambda work, compared with the Java you know.

Left, a Java sheet tagged 3 methods: three overloads of summarize taking text, then text and maxWords, then text, maxWords and style. An arrow points right to a yellow Python sheet tagged 1 function: def summarize with text, max_words equals 50 and style equals plain, and a call summarize doc, style equals bullets. Caption: name the argument you change, skip the rest.
Fig. 1 — Three Java overloads become one Python function with defaults. Callers name only what they change.

Look at any Python AI SDK call and you’ll see something like this:

reply = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=500,
    temperature=0.2,
    messages=messages,
)

In Java, the same API would be a builder with a dozen methods, or a request object with setters. In Python it’s one function call with named arguments. Once you understand how Python functions take arguments, most library APIs suddenly read like plain English.

This is part 5 of Python for Java Developers. Part 4 covered list and dict, which you’ll pass to most functions.

def: a function on its own

public static String greet(String name) {
    return "Hello, " + name;
}
def greet(name):
    return f"Hello, {name}"

def, a name, parameters, a colon, an indented body. No access modifier, no static, no return type, and no class needed around it. A function that never reaches a return gives back None.

To return more than one value, return a tuple and unpack it:

def min_max(nums):
    return min(nums), max(nums)

low, high = min_max([4, 1, 9])

Default values replace overloading

Python has no method overloading. If you define greet twice, the second definition simply replaces the first. Instead, you give parameters default values:

String summarize(String text) { return summarize(text, 50); }
String summarize(String text, int maxWords) { return summarize(text, maxWords, "plain"); }
String summarize(String text, int maxWords, String style) { ... }
def summarize(text, max_words=50, style="plain"):
    ...

summarize(article)              # both defaults
summarize(article, 100)         # max_words=100, style="plain"

(... is real Python, called Ellipsis. In examples it means “the body goes here”, and it’s a valid placeholder body.)

Parameters with defaults must come after the ones without, as you’d expect.

Keyword arguments replace builders

Any argument can be passed by name, in any order:

summarize(article, style="bullets")               # skip max_words
summarize(style="bullets", text=article, max_words=80)

That’s the trick behind every readable Python API. In Java you reach for a builder so callers can set only what they need and the call stays readable:

var request = ChatRequest.builder()
    .model("claude-sonnet-5-5")
    .maxTokens(500)
    .temperature(0.2)
    .build();
request = ChatRequest(
    model="claude-sonnet-5-5",
    max_tokens=500,
    temperature=0.2,
)

Same readability, no builder class to write. Read every name=value as one builder call.

Keyword-only arguments

Library functions often put a bare * in their signature. Everything after it must be passed by name:

def search(query, *, top_k=5, filters=None):
    ...

search("rag", top_k=10)     # fine
search("rag", 10)           # TypeError: top_k must be named

Library authors use this so they can add or reorder options later without breaking your code. When you see a * alone in a signature, that’s what it means.

*args and **kwargs

You’ll read these more often than you write them.

  • *args collects extra positional arguments into a tuple. It’s Java’s varargs, String... args.
  • **kwargs collects extra keyword arguments into a dict. Java has no equivalent.
def log(message, *args, **kwargs):
    print(message, args, kwargs)

log("hi", 1, 2, user="asha", level="debug")
# hi (1, 2) {'user': 'asha', 'level': 'debug'}

The names args and kwargs are only a convention; the stars do the work. Wrapper functions use them to pass everything through to another function:

import time

def timed_call(func, *args, **kwargs):
    start = time.time()
    result = func(*args, **kwargs)      # forward everything
    print(f"took {time.time() - start:.2f}s")
    return result

Stars that unpack

The same stars work the other way at the call site: * spreads a list into positional arguments, and ** spreads a dict into keyword arguments.

settings = {"model": "claude-sonnet-5-5", "max_tokens": 500}
client.messages.create(**settings, messages=messages)
# same as create(model="claude-sonnet-5-5", max_tokens=500, messages=messages)

AI code uses this to keep model settings in one dict and reuse them across calls.

Functions are values

A Python function is an object. You can store it in a variable, put it in a dict, or pass it to another function, like a Java method reference:

handlers = {"text": show_text, "tool_use": run_tool}
handlers[event.type](event)          # look up and call

Small one-off functions are written with lambda. A Python lambda holds a single expression, no statements:

hits.sort(Comparator.comparing(Hit::score).reversed());
Function<Integer, Integer> square = x -> x * x;
hits.sort(key=lambda h: h.score, reverse=True)
square = lambda x: x * x        # works, but a def is clearer

If a lambda grows beyond one short expression, write a def instead.

Docstrings: Python’s Javadoc

The first string inside a function is its docstring. Editors show it on hover, help(summarize) prints it, and AI frameworks even send it to the model to describe a tool:

def summarize(text, max_words=50, style="plain"):
    """Summarize text in at most max_words words.

    style is "plain" or "bullets".
    """
    ...

The mutable default trap

This bug catches nearly every Java developer once. A default value is created one time, when Python reads the def, and then shared by every call:

def add_message(msg, history=[]):        # wrong
    history.append(msg)
    return history

add_message("a")    # ['a']
add_message("b")    # ['a', 'b']   the same list again!

The fix is to default to None and create the list inside:

def add_message(msg, history=None):      # right
    if history is None:
        history = []
    history.append(msg)
    return history

The rule: never use a list, dict or set as a default value. Strings, numbers, True/False and None are safe because they can’t change.

Key takeaways

  • def name(params): defines a function; it can live outside any class and returns None by default.
  • There’s no overloading. Default values cover it: def f(text, max_words=50):.
  • Keyword arguments (f(style="bullets")) replace builders and make calls self-documenting.
  • A bare * in a signature means “everything after this must be named”.
  • *args is varargs, **kwargs collects named extras, and **settings spreads a dict into a call.
  • A lambda is one expression. Use def for anything longer.
  • Never use a mutable value as a default; use None and create it inside.

Frequently asked questions

Does Python support method overloading?

No. A second def with the same name replaces the first. Use default values, keyword arguments, or *args to accept different combinations of arguments in one function.

What are keyword arguments in Python?

Arguments passed by name, like summarize(article, style="bullets"). They can come in any order after the positional ones, and they make calls readable without a builder.

What do *args and **kwargs mean in Python?

*args collects extra positional arguments into a tuple, like Java varargs. **kwargs collects extra named arguments into a dict. At a call site, * and ** do the reverse: they spread a list or dict into arguments.

Is a Python lambda the same as a Java lambda?

Similar in purpose, more limited in form. A Python lambda can contain only one expression, with no statements or blocks. For anything longer, define a normal function with def and pass it by name.

Why shouldn’t I use a list as a default argument in Python?

Because the default is created once and shared by every call that uses it. Items added in one call are still there in the next. Default to None and create a new list inside the function.

Next in the series: Python classes, dataclasses and Pydantic, and how Python’s answer to Java records validates your data too.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.