Telegram Group & Telegram Channel
This media is not supported in your browser
VIEW IN TELEGRAM
🖥 Python-лайфхак для профи: “Перехват любого импорта” с помощью import hooks

Хотите логировать или модифицировать поведение импортируемых модулей?
Используйте механизм sys.meta_path и свои кастомные import hooks!

Зачем это нужно:
• Автоматический патчинг сторонних библиотек
• Логирование импорта для аудита или отладки
• Подмена модулей “на лету” для тестирования или “горячих фиксов”

Пример — ловим каждый импорт и выводим имя модуля:


import sys

class ImportLoggerFinder:
def find_spec(self, fullname, path, target=None):
print(f'Импортируется: {fullname}')
return None # Не вмешиваемся, просто логируем

sys.meta_path.insert(0, ImportLoggerFinder())

# Теперь при любом импорте будет выводиться имя загружаемого модуля


import json
import math
import requests

# Вы увидите:
# Импортируется: json
# Импортируется: math
# Импортируется: requests


С помощью такого подхода можно делать глубокий аудит, динамические патчи или реализовать кастомные протоколы импорта для своих нужд. Очень мощный, но малоизвестный инструмент стандартной библиотеки!

Сохрани себе, чтобы не потерять 😎
Please open Telegram to view this post
VIEW IN TELEGRAM



group-telegram.com/data_math/787
Create:
Last Update:

🖥 Python-лайфхак для профи: “Перехват любого импорта” с помощью import hooks

Хотите логировать или модифицировать поведение импортируемых модулей?
Используйте механизм sys.meta_path и свои кастомные import hooks!

Зачем это нужно:
• Автоматический патчинг сторонних библиотек
• Логирование импорта для аудита или отладки
• Подмена модулей “на лету” для тестирования или “горячих фиксов”

Пример — ловим каждый импорт и выводим имя модуля:


import sys

class ImportLoggerFinder:
def find_spec(self, fullname, path, target=None):
print(f'Импортируется: {fullname}')
return None # Не вмешиваемся, просто логируем

sys.meta_path.insert(0, ImportLoggerFinder())

# Теперь при любом импорте будет выводиться имя загружаемого модуля


import json
import math
import requests

# Вы увидите:
# Импортируется: json
# Импортируется: math
# Импортируется: requests


С помощью такого подхода можно делать глубокий аудит, динамические патчи или реализовать кастомные протоколы импорта для своих нужд. Очень мощный, но малоизвестный инструмент стандартной библиотеки!

Сохрани себе, чтобы не потерять 😎

BY Математика Дата саентиста


Share with your friend now:
group-telegram.com/data_math/787

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

Russians and Ukrainians are both prolific users of Telegram. They rely on the app for channels that act as newsfeeds, group chats (both public and private), and one-to-one communication. Since the Russian invasion of Ukraine, Telegram has remained an important lifeline for both Russians and Ukrainians, as a way of staying aware of the latest news and keeping in touch with loved ones. The regulator said it had received information that messages containing stock tips and other investment advice with respect to selected listed companies are being widely circulated through websites and social media platforms such as Telegram, Facebook, WhatsApp and Instagram. "This time we received the coordinates of enemy vehicles marked 'V' in Kyiv region," it added. On Feb. 27, however, he admitted from his Russian-language account that "Telegram channels are increasingly becoming a source of unverified information related to Ukrainian events." What distinguishes the app from competitors is its use of what's known as channels: Public or private feeds of photos and videos that can be set up by one person or an organization. The channels have become popular with on-the-ground journalists, aid workers and Ukrainian President Volodymyr Zelenskyy, who broadcasts on a Telegram channel. The channels can be followed by an unlimited number of people. Unlike Facebook, Twitter and other popular social networks, there is no advertising on Telegram and the flow of information is not driven by an algorithm.
from us


Telegram Математика Дата саентиста
FROM American