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

The gold standard of encryption, known as end-to-end encryption, where only the sender and person who receives the message are able to see it, is available on Telegram only when the Secret Chat function is enabled. Voice and video calls are also completely encrypted. Although some channels have been removed, the curation process is considered opaque and insufficient by analysts. The channel appears to be part of the broader information war that has developed following Russia's invasion of Ukraine. The Kremlin has paid Russian TikTok influencers to push propaganda, according to a Vice News investigation, while ProPublica found that fake Russian fact check videos had been viewed over a million times on Telegram. Markets continued to grapple with the economic and corporate earnings implications relating to the Russia-Ukraine conflict. “We have a ton of uncertainty right now,” said Stephanie Link, chief investment strategist and portfolio manager at Hightower Advisors. “We’re dealing with a war, we’re dealing with inflation. We don’t know what it means to earnings.” The regulator said it has been undertaking several campaigns to educate the investors to be vigilant while taking investment decisions based on stock tips.
from in


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