1
$\begingroup$

I have a class PG_Parameters (PropertyGroup) where all the addon parameters are stored. I would like to create a dictionary, where keys are names of the properties and the values are the values of the properties.

Typically a dictionary of class variables could be created like this:

dict = {key:value for key, value in PG_Parameters.__dict__.items() if not key.startswith('__') and not callable(key)}

But the resulting dictionary is:

{'bl_rna': <bpy_struct, Struct("PG_Parameters")>}

But I would like to get:

{'my_int': 1, 'my_float': 2.3, 'my_string': "example_string"}

How could I approach this?

$\endgroup$
1
$\begingroup$

You can use __annotations__ to access your custom properties instead of your conditional list comprehension:

import bpy

my_props = bpy.context.scene.my_props  # Access your custom properties (Replace if needed)
props_dic = '{'  # Open dictionary
for prop_name in my_props.__annotations__:  # Loop over all custom properties names
    value = getattr(my_props, prop_name)  # Access this particular prop value
    value_str = f"'{value}'" if type(value) is str else str(value)  # Transform it to string or add commas if it is already a string
    props_dic += f"'{prop_name}': {value_str}, "  # Add a new entry in the dictionary
props_dic += '}'  # Close dictionary
print(props_dic)

Be aware though that it will only work for 'simple' values, like floats, strings and booleans. If you have more complexe values, like Vectors you will have to add that to your parsing method.

Further and further reading.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.