Home > Mobile >  How to retrieve stored Python object from dictionary?
How to retrieve stored Python object from dictionary?

Time:12-07

I have a Python dictionary dict1:

import gradio as gr

dict1 = {
    "x" : 2,
    "y" : 110,
    "z" : gr.Dropdown(label="zip", choices=["12345", "98765"], value="44445")
}

The key z contains a Gradio object.

In the next step I want to convert all my dict keys to proper variables:

for var in dict1:
    locals()[var] = dict1[var]

This kind of works as you can see:

print(dict1)
print(x,y, z)
type(z)
>>>> {'x': 2, 'y': 110, 'z': dropdown}
>>>> 2 110 dropdown
>>>> gradio.components.Dropdown

However, the object in dict1 is not showing all informations. Its still an object but I want z to be z = gr.Dropdown(label="zip", choices=["12345", "98765"], value="44445"). At the moment it is z = dropdown

How can I do it?

CodePudding user response:

Once gr.Dropdown is constructed Python interpretor won't know which parameters were used to construct the object.

But you can print all fields of the object with the following function:

def pretty_print(clas, indent=0):
    print(' ' * indent    type(clas).__name__    ':')
    indent  = 4
    for k,v in clas.__dict__.items():
        print(' ' * indent    k   ': '   str(v))

Now you can run:

pretty_print(dict1['z'])

to get the output:

Dropdown:
    choices: ['12345', '98765']
    type: value
    test_input: 12345
    interpret_by_tokens: False
    label: zip
    show_label: True
    requires_permissions: False
    interactive: None
    value: 44445
    attach_load_event: False
    load_fn: None
    _id: 0
    visible: True
    elem_id: None
    root_url: None
    _style: {}
    cleared_value: 44445

This output contains more fields but the useful fields are all here.

  • Related