🖥 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
С помощью такого подхода можно делать глубокий аудит, динамические патчи или реализовать кастомные протоколы импорта для своих нужд. Очень мощный, но малоизвестный инструмент стандартной библиотеки!
🖥 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
С помощью такого подхода можно делать глубокий аудит, динамические патчи или реализовать кастомные протоколы импорта для своих нужд. Очень мощный, но малоизвестный инструмент стандартной библиотеки!
Emerson Brooking, a disinformation expert at the Atlantic Council's Digital Forensic Research Lab, said: "Back in the Wild West period of content moderation, like 2014 or 2015, maybe they could have gotten away with it, but it stands in marked contrast with how other companies run themselves today." The S&P 500 fell 1.3% to 4,204.36, and the Dow Jones Industrial Average was down 0.7% to 32,943.33. The Dow posted a fifth straight weekly loss — its longest losing streak since 2019. The Nasdaq Composite tumbled 2.2% to 12,843.81. Though all three indexes opened in the green, stocks took a turn after a new report showed U.S. consumer sentiment deteriorated more than expected in early March as consumers' inflation expectations soared to the highest since 1981. Again, in contrast to Facebook, Google and Twitter, Telegram's founder Pavel Durov runs his company in relative secrecy from Dubai. In view of this, the regulator has cautioned investors not to rely on such investment tips / advice received through social media platforms. It has also said investors should exercise utmost caution while taking investment decisions while dealing in the securities market. Soloviev also promoted the channel in a post he shared on his own Telegram, which has 580,000 followers. The post recommended his viewers subscribe to "War on Fakes" in a time of fake news.
from ye