Using bound argument name inside python function

68 Views Asked by At

My current hackish manner of printing multiple arrays in columns uses keyword arguments to label the output:

def table(**data_dict):
    n=([len(x) for x in data_dict.values()]) # # data for each var
    N=max(n)
    # prep data & print headings
    prntstr=''
    for i,var in enumerate(data_dict):
        # convert lists to str for printing, padding as needed
        data_dict[var] = ['{:.5g}'.format(x) for x in data_dict[var]] + ['']*(N-n[i]) 
        prntstr=prntstr+f'| {var:^8} |'
    print(prntstr,'-'*12*len(data_dict),sep='\n'); # print heading 
    # print data
    for i in range(0,N):
        prntstr=' '.join(f'{data_dict[var][i]:>11}' for var in data_dict)
        print(prntstr)

and used

rho=[1.5,0.11]
Fx=[-14.2]
table(rho=rho,T=[665,240],Fx=Fx)

producing

|   rho    ||    T     ||    Fx    |
------------------------------------
        1.5         665       -14.2
       0.11         240

Is there another way to do this that can use the bound argument name (e.g rho) and avoid the repetition (e.g. rho=rho) for non-keyword arguments so that one could type simply table(rho,T=[665,240],Fx)? Thank you in advance.

1

There are 1 best solutions below

0
On

Use RHO=rho where RHO is the heading in the output.

Replace

table(rho=rho,T=[665,240],Fx=Fx)

with

table(RHO=rho,T=[665,240],Fx=Fx)

If this is not acceptable you will have to accept the first argument

Replace

def table(**data_dict)

with

def table(RHO, **data_dict):
    data_dict['rho'] = RHO

and call as follows:

Replace

table(rho=rho,T=[665,240],Fx=Fx)

with

table(rho,T=[665,240],Fx=Fx)