Search code examples
pythonnumpyformatter

confused about formatter in numpy. set_printoptions


I encountered the following piece of code:

z=np.arange(0,12)
np.set_printoptions(formatter=dict(int=lambda x: f'{x:4}'))
print(z)

I understand what the code is doing but I am not clear as to what the quantity inside the brackets of dict() is. Without int= we have a function. In numpy docs the value of formatter should be a dict of callables. The keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. So shouldn't it be int: instead of int=? I got a synatx error when I tried that


Solution

  • The notation int= is just keyword argument, passed to the method dict(), that is equivalent to

    fmt = {"int": lambda x: f'{x:4}'}
    

    Other example

    fmt = dict(int=lambda x: f'{x:4}', float=lambda x: f'{x:4}')
    fmt = {"int": lambda x: f'{x:4}', 'float': lambda x: f'{x:10}'}
    fmt = dict(int=lambda x: f'{x:4}', float=lambda x: f'{x:10}')
    fmt = {"int": lambda x: f'{x:4}', 'float': lambda x: f'{x:10}'}
    
    value = 1
    print(fmt[type(value).__name__](value))  #    1
    
    value = 1.1
    print(fmt[type(value).__name__](value))  #           1.1