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: |

Perpetrators of such fraud use various marketing techniques to attract subscribers on their social media channels. The War on Fakes channel has repeatedly attempted to push conspiracies that footage from Ukraine is somehow being falsified. One post on the channel from February 24 claimed without evidence that a widely viewed photo of a Ukrainian woman injured in an airstrike in the city of Chuhuiv was doctored and that the woman was seen in a different photo days later without injuries. The post, which has over 600,000 views, also baselessly claimed that the woman's blood was actually makeup or grape juice. However, the perpetrators of such frauds are now adopting new methods and technologies to defraud the investors. Two days after Russia invaded Ukraine, an account on the Telegram messaging platform posing as President Volodymyr Zelenskiy urged his armed forces to surrender. "The argument from Telegram is, 'You should trust us because we tell you that we're trustworthy,'" Maréchal said. "It's really in the eye of the beholder whether that's something you want to buy into."
from us


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