pythonformatclass-methoddefault-arguments

Default argument inside method


I try to implement format for a class. I want to have an argument that defaults to 'short'.

I tried:

def __format__(self, code='short'):
    if code == 'short':
        return f'Filename {self.filename}: {self.config}'
    elif code == 'long':
        string = f'{self.filename}'
        for key, value in self.config.items():
           string = string + f'\n{key}{self.sep}{value}'
        return string
    else:
        raise TypeError('Choose between short or long.')

my_config_file = ConfigFileWithBackups('mycofig.txt')
print(f'{my_config_file}')

This last call raises the TypeError but I expected to default to 'short' implementation. Any ideas why?

Of course I can use something like: if not code or code == 'short' but I hope I can understand what's going on with my initial implementation.


Solution

  • The __format__ method will be invoked with a format_spec which, in your case, will be an empty string. A value will always be passed. Therefore, setting a default is pointless. Do you realise that you could do this:- print(f'{my_config_file:short}') Either that or if the format_spec is an empty string then assume that's equivalent to 'short'

    class ConfigFileWithBackups:
        def __init__(self, filename):
            self.filename = filename
            self.config = {}
            self.sep = ':'
        def __format__(self, format_spec):
            match format_spec:
                case '' | 'short':
                    return f'Filename {self.filename}: {self.config}'
                case 'long':
                    string = f'{self.filename}'
                    for key, value in self.config.items():
                        string = string + f'\n{key}{self.sep}{value}'
                    return string
            raise TypeError('Choose between short or long.')
    
    my_config_file = ConfigFileWithBackups('myconfig.txt')
    
    try:
        print(f'{my_config_file}')
        print(f'{my_config_file:short}')
        print(f'{my_config_file:long}')
        print(f'{my_config_file:foo}')
    except TypeError as e:
        print(e)
    

    Output:

    Filename myconfig.txt: {}
    Filename myconfig.txt: {}
    myconfig.txt
    Choose between short or long.