DEV Community

Steven Hur
Steven Hur

Posted on

Optuna f-string Refactoring

Hello! Just submitted my 4th PR to open source. This time it's Optuna.

What is Optuna?
Optuna is a hyperparameter optimization framework for machine learning. Basically when you're training ML models, you have tons of parameters to tune - learning rate, batch size, number of layers, etc. Optuna automates this process using smart algorithms instead of random guessing.
What makes it interesting is the define-by-run API. You can dynamically construct search spaces, which is way more flexible than traditional grid search or random search. It's used by a lot of ML practitioners and has integrations with PyTorch, TensorFlow, XGBoost, and basically every major ML library.

What I Did
Found this issue asking to replace old .format() with f-strings. Some what simple refactoring.
issue-6305

They wanted this:

Old way (ugly)
"{cls}({kwargs})".format(cls=..., kwargs=...)

New way (clean)
f"{cls}({kwargs})"
Enter fullscreen mode Exit fullscreen mode

The Code Change
Changed this old python 3.8 style:

def __repr__(self) -> str:
    return "{cls}({kwargs})".format(
        cls=self.__class__.__name__,
        kwargs=", ".join(
            "{field}={value}".format(
                field=field if not field.startswith("_") else field[1:],
                value=repr(getattr(self, field)),
            )
            for field in self.__dict__
        )
        + ", value=None",
    )
Enter fullscreen mode Exit fullscreen mode

Into this:

def __repr__(self) -> str:
    kwargs = ", ".join(
        f"{field if not field.startswith('_') else field[1:]}={getattr(self, field)!r}"
        for field in self.__dict__
    ) + ", value=None"
    return f"{self.__class__.__name__}({kwargs})"
Enter fullscreen mode Exit fullscreen mode

Key Points
The main change was replacing all .format() calls with f-strings, which is the modern Python way since 3.8+. I also used !r instead of calling repr() directly because that's more pythonic in f-strings. The issue specifically asked for one file per PR to make reviews easier, so I only touched this single file.

Why This is Easy
This is just syntax conversion with no logic changes at all. The output stays exactly the same, just written differently. The issue had clear examples showing exactly what they wanted, so there was zero guesswork involved. Best part is tests won't break because the functionality is identical, just cleaner code.

This issue was some what easier then what I've been doing but I wanted to contribute to this project because Optuna is a framework that I've been studying recently. It does feel much comfortable compare to the first contribution that I made to Scikit-learn. I guess I am improving in some way through this process.

Top comments (0)