J.G
J.G

Reputation: 307

Special way of returning a dictionary?

In a certain function, I used many variables for different usages. I would like to return them, but return var_1, var_2, ..., var_100, ..., var_n is clearly not pythonic. I thought creating a dict kwargs = {"var1": var_1, "var2": var_2, ..., "var_100": var_100, ..., "var_n": var_n} and returning the dict, but the dict is way too long and it is not pythonic either.

A solution might be to return dict(var.__name__ : var for var in var_list) (pseudocode). Clearly, that solution won't work. Is there a way to do that? Is there a way to display the name of a variable, i.e the equivalence of var.__name__ if I can say?

Upvotes: 0

Views: 64

Answers (1)

rdas
rdas

Reputation: 21275

You could return locals()

def a_func():
       a = 10
       b = 'a'
       c = 100
       d = 500
       e = False

       return locals()

retval = a_func()
print(retval)

Output:

{'a': 10, 'b': 'a', 'c': 100, 'd': 500, 'e': False}

You can also have some filtering (instead of returning all the locals):

    ...
    return {k:v for k,v in locals().items() if ...}

Upvotes: 4

Related Questions