get_init_args#

dpeeg.utils.get_init_args(obj, locals: dict, format: str = 'log', rename: str | None = None, ret_dict: Literal[False] = False, **kwargs) str[source]#
dpeeg.utils.get_init_args(obj, locals: dict, format: str = 'log', rename: str | None = None, ret_dict: Literal[True] = True, **kwargs) dict

Get object initialization parameters.

Assemble the parameters passed in by class initialization or function according to the specified format. The function can return either the assembled string or the unassembled dictionary for updating internal parameters.

Parameters:
  • obj (class, function) – The kind of class or function.

  • locals (dict) – Local parameters in class.__init__ or function.

  • format (str) – Parameters splicing format. - log: [name nt param1 nt param2 nt …] - rp: name(param1, param2, …)

  • rename (str, optional) – User renamed name. If None, the default class or function name is used.

  • ret_dict (bool) – If True, return the initialization parameters as a dictionary, ignoring the format parameter. By default, return a string in the specified format.

  • **kwargs (dict, optional) – Additional parameters for format assembly.

Returns:

  • str – A string specifying the format.

  • dict – A dictionary containing initialization parameters.

Examples

When you want to get the parameters of a class and its methods. Note: It is best to use self as the obj parameter during initialization and avoid using the class to prevent class_name recognition errors of inherited classes.

>>> class Base:
...     def __init__(self, param1, param2=2) -> None:
...         print(get_init_args(self, locals(), "rp"))
...     def method(self, param3):
...         print(get_init_args(self.method, locals(), "rp"))
>>> class Sub(Base):
...     pass
>>> obj_base = Base(1)
Base(param1=1, param2=2)
>>> obj_base.method(3)
Base.method(param3=3)
>>> obj_sub = Sub(1)
Sub(param1=1, param2=2)
>>> obj_sub.method(3)
Sub.method(param3=3)

Likewise, functions are supported.

>>> def func(param1, param2 = 2):
...     print(get_init_args(func, locals(), "rp"))
>>> func(1)
func(param1=1, param2=2)

You can also rename these:

>>> class Base:
...     def method(self, param):
...         print(get_init_args(self.method, locals(), "rp", "Sub.func"))
>>> obj = Base()
>>> obj.method(4)
Sub.func(param=4)