Created
February 9, 2021 06:10
-
-
Save AlonsoMackenlly/66f0fa53537ff486a856c1d06b7f55a6 to your computer and use it in GitHub Desktop.
Импорт класса по строковому пути к модулю
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import importlib | |
from typing import Any, Optional | |
def import_class_by_path(path: str) -> Optional[Any]: | |
""" Делает динамический импорт класса по пути типа apps.app.lib.classes.MyClass """ | |
# Разбиваем модули на куски | |
modules = path.split('.') | |
# Берем конечный модуль из которого импортируем класс | |
modules_path = ".".join(modules[:-1]) | |
# Импортируем модуль через importlib | |
module_ = importlib.import_module(modules_path) | |
# Получаем нужный класс или None, если не найден | |
handler_cls = getattr(module_, modules[-1], None) | |
return handler_cls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment