PYTHONL Telegram 4922
This media is not supported in your browser
VIEW IN TELEGRAM
🧠 Как превратить любой Python-объект в читаемый словарь — даже если это класс с кучей вложенных полей

Когда работаешь с API, логами или дебажишь сложные объекты — хочется увидеть весь объект как словарь, без .__dict__, без сериализации, без ручного разбора.

Вот приём, который делает это рекурсивно, красиво и гибко — с помощью dataclasses и asdict, даже если объект не был dataclass изначально.

python 
from dataclasses import dataclass, asdict, is_dataclass
from types import SimpleNamespace

def deep_to_dict(obj):
if isinstance(obj, dict):
return {k: deep_to_dict(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [deep_to_dict(i) for i in obj]
elif is_dataclass(obj):
return asdict(obj)
elif isinstance(obj, SimpleNamespace):
return deep_to_dict(vars(obj))
elif hasattr(obj, '__dict__'):
return deep_to_dict(vars(obj))
else:
return obj


🧠 Рекурсивный разбор любых Python-объектов

📌 Подходит для логирования, сериализации, отладки
📌 Работает с dataclass, обычными классами, объектами из types, JSON-like структурами
📌 Можно расширить: добавить фильтрацию полей, вывод в YAML или сохранение в файл

Теперь любой “монстр из API” — превращается в читаемый словарь за одну строчку.
👍117🔥4🤩1



tgoop.com/pythonl/4922
Create:
Last Update:

🧠 Как превратить любой Python-объект в читаемый словарь — даже если это класс с кучей вложенных полей

Когда работаешь с API, логами или дебажишь сложные объекты — хочется увидеть весь объект как словарь, без .__dict__, без сериализации, без ручного разбора.

Вот приём, который делает это рекурсивно, красиво и гибко — с помощью dataclasses и asdict, даже если объект не был dataclass изначально.

python 
from dataclasses import dataclass, asdict, is_dataclass
from types import SimpleNamespace

def deep_to_dict(obj):
if isinstance(obj, dict):
return {k: deep_to_dict(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [deep_to_dict(i) for i in obj]
elif is_dataclass(obj):
return asdict(obj)
elif isinstance(obj, SimpleNamespace):
return deep_to_dict(vars(obj))
elif hasattr(obj, '__dict__'):
return deep_to_dict(vars(obj))
else:
return obj


🧠 Рекурсивный разбор любых Python-объектов

📌 Подходит для логирования, сериализации, отладки
📌 Работает с dataclass, обычными классами, объектами из types, JSON-like структурами
📌 Можно расширить: добавить фильтрацию полей, вывод в YAML или сохранение в файл

Теперь любой “монстр из API” — превращается в читаемый словарь за одну строчку.

BY Python/ django


Share with your friend now:
tgoop.com/pythonl/4922

View MORE
Open in Telegram


Telegram News

Date: |

In handing down the sentence yesterday, deputy judge Peter Hui Shiu-keung of the district court said that even if Ng did not post the messages, he cannot shirk responsibility as the owner and administrator of such a big group for allowing these messages that incite illegal behaviors to exist. The optimal dimension of the avatar on Telegram is 512px by 512px, and it’s recommended to use PNG format to deliver an unpixelated avatar. Telegram channels fall into two types: How to create a business channel on Telegram? (Tutorial) The initiatives announced by Perekopsky include monitoring the content in groups. According to the executive, posts identified as lacking context or as containing false information will be flagged as a potential source of disinformation. The content is then forwarded to Telegram's fact-checking channels for analysis and subsequent publication of verified information.
from us


Telegram Python/ django
FROM American