overriding a class’s format and setting its mode in python

For your object’s format method to return something that itself has a format method, you probably want to create another class.

class Formatter:
    def __init__(self, mode: str) -> None:
        self._mode = mode

    def format(self, *args: str) -> str:
        if self._mode == 'spaces':
            return ' '.join(args)
        elif self._mode == 'commas':
            return ', '.join(args)
        raise ValueError(f"invalid formatting mode {self._mode}")

class Foo:
    def format(self, mode: str) -> Formatter:
        return Formatter(mode)

foo = Foo()
print(foo.format("commas").format('arg1', 'arg2'))
# arg1, arg2

It might be easier if the first format returned a single function you could call directly rather than an object with a single method; that would allow you to simply define the function inline, which might be preferable if the formatting logic is relatively simple. (It’s also kinda confusing IMO to have code with two format methods that do completely different things!) Here’s how that might look:

class Foo:
    def format(self, mode: str) -> callable:
        def formatter(*args: str) -> str:
            if mode == 'spaces':
                return ' '.join(args)
            elif mode == 'commas':
                return ', '.join(args)
            raise ValueError(f"invalid formatting mode {mode}")
        return formatter

foo = Foo()
print(foo.format("commas")('arg1', 'arg2'))
# arg1, arg2

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top