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

Groups are also not fully encrypted, end-to-end. This includes private groups. Private groups cannot be seen by other Telegram users, but Telegram itself can see the groups and all of the communications that you have in them. All of the same risks and warnings about channels can be applied to groups. On Telegram’s website, it says that Pavel Durov “supports Telegram financially and ideologically while Nikolai (Duvov)’s input is technological.” Currently, the Telegram team is based in Dubai, having moved around from Berlin, London and Singapore after departing Russia. Meanwhile, the company which owns Telegram is registered in the British Virgin Islands. Just days after Russia invaded Ukraine, Durov wrote that Telegram was "increasingly becoming a source of unverified information," and he worried about the app being used to "incite ethnic hatred." Ukrainian forces successfully attacked Russian vehicles in the capital city of Kyiv thanks to a public tip made through the encrypted messaging app Telegram, Ukraine's top law-enforcement agency said on Tuesday. At this point, however, Durov had already been working on Telegram with his brother, and further planned a mobile-first social network with an explicit focus on anti-censorship. Later in April, he told TechCrunch that he had left Russia and had “no plans to go back,” saying that the nation was currently “incompatible with internet business at the moment.” He added later that he was looking for a country that matched his libertarian ideals to base his next startup.
from it


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