giampaolo / psutil

Cross-platform lib for process and system monitoring in Python
BSD 3-Clause "New" or "Revised" License
10.31k stars 1.39k forks source link

[Linux] Add support for Dict[str, Any] signature for ad_value parameter in psutil.Process.as_dict(..) #2336

Closed h4l7 closed 11 months ago

h4l7 commented 11 months ago

Summary

Proposal to support Dict[str, Any] parameters for ad_value, so that each key provided in attrs may have a custom default value.

Description

As defined, as_dict(attrs=None, ad_value=None) only accepts a single default value for all keys provided in attrs. This means that it's not possible to have different default values for each key in attrs.

For example, consider:

attrs = ["connections", "cwd", "environ", "io_counters", "memory_full_info", "num_fds", "open_files"]
ad_values = {
  "connections": [],
  "cwd": "",
  "environ": {},
  "io_counters": psutil._pslinux.pio(
    read_count=0, write_count=0, read_bytes=0, write_bytes=0, read_chars=0, write_chars=0
  ),
  "memory_full_info": psutil._pslinux.pfullmem(
    rss=0, vms=0, shared=0, text=0, lib=0, data=0, dirty=0, uss=0, pss=0, swap=0
  ),
  "num_fds": 0,
  "open_files": [],
}
stats = proc.as_dict(attrs=attrs, ad_values=ad_values)

Relevant code snippet:

https://github.com/giampaolo/psutil/blob/master/psutil/__init__.py#L545

Function docs

https://psutil.readthedocs.io/en/latest/index.html#psutil.Process.as_dict

Thank you for your consideration.

giampaolo commented 11 months ago

Nope, it makes the API too complex both to use and to document.

Also, there would be no way to distinguish between "return {} for all APIs" vs. "here is a dict describing what each API should return", because they are both dicts.

If you want such a level of customization you are better off using the native APIs directly (cwd(), exe(), etc.), or write your own wrapper on top of them in way that is similar to as_dict().