Skip to content

How to get init args & values of a class instance #2341

@Nic-Ma

Description

@Nic-Ma

Hi @ericspod @wyli @vfdev-5 ,

I got an important feature request from the internal team: how to get the init args and the values from a MONAI or ignite class instance and then used for logging or exporting to JSON files, etc.
For example:

from monai.transforms import LoadImaged
load_image = LoadImaged(keys=["image", "seg"], meta_key_postfix="11")

How to get {"keys": ["image", "seg"], "meta_key_postfix": "11"} from the load_image instance?
I tried inspect, but seems it can only get the self.XXX instead of the real original init args, here is my test program:

class MONAIClass:
    def __init__(self, keys, count, flag) -> None:
        self.keys = keys
        self.count = count * 10
        print(flag)

load_image = MONAIClass(keys=["image", "seg"], count=1, flag="in class")
import inspect
signature = inspect.signature(load_image.__class__)
print(f"class name: {load_image.__class__}")
print("Arguments")
for key in signature.parameters:
    try:
        value = getattr(load_image, key)
    except Exception as e:
        value = signature.parameters[key].default
    print(key, ":", value)

And the the output:

class name: <class '__main__.TestAddChanneld.test_class.<locals>.MONAIClass'>
Arguments
keys : ['image', 'seg']
count : 10
flag : <class 'inspect._empty'>

count and flag are not correct here.
Do you python experts have some cool ideas for this problem?
I am blocked by this problem and didn't get a good solution so far, appreciate any help here!

Thanks in advance.

Metadata

Metadata

Labels

questionFurther information is requested

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions