Idea: Support lazy imports and defer schema initialization

Đang mở
#752 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
35/100
Loại issue
Tính năng
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
python, sqlalchemy
Lĩnh vực
backend

Hướng nghiên cứu

Start by reading the schema model configuration and initialization paths in marshmallow-sqlalchemy, then compare them with the proof of concept in the issue. Determine whether lazy model resolution can be supported without triggering mapper setup or circular imports during module import. Done means schemas can defer initialization until instantiation while preserving existing behavior; the issue does not name specific files or tests.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

The idea is to pass a lazy_import proxy as the model of a Schema and only trigger the schema initialization the first time it's instantiated.

This would avoid triggering SQLAlchemy mapper setup during import time which can cause problems when not all models have been imported yet at that point, and also avoid issues with circular imports between modules defining schemas and modules defining db models.

Here's a small proof of concept how it could work (w/o any MM code, just to show the general idea):

# schemas.py
print('schemas.py import start')
import typing
from types import LazyImportType

lazy from models import SomeModel


class Schema:
    def __init__(self):
        self.model = getattr(self, 'model', None) or typing.get_type_hints(type(self))['model']
        # only needed when suing the `global()` variant below; with the type int it's being resolved above
        if isinstance(self.model, LazyImportType):
            self.model = self.model.resolve()

    def __repr__(self):
        return f'<{type(self).__name__}({self.model.__name__})>'


class SomeSchema(Schema):
    # doesn't work since it triggers reification:
    # model = SomeModel

    # this works but it's ugly
    # model = globals()['SomeModel']

    # this also works and is not super ugly, but a bit weird to use a type annotation for this
    model: SomeModel


def main():
    print('schemas.main - instantiating SomeSchema')
    print(SomeSchema())


print('schemas.py import done')

if __name__ == '__main__':
    main()
# models.py
print('models.py import start')

class SomeModel:
    pass

print('models.py import done')

When running it:

$ python lazytest/schemas.py
schemas.py import start
schemas.py import done
schemas.main - instantiating SomeSchema
models.py import start
models.py import done
<SomeSchema(SomeModel)>

The somewhat ugly part is of course that accessing a lazy import by name immediately triggers the actual import, I don't think Python has a nice way to pass this imported symbol without it being reified. The easiest way to avoid it is accessing it via globals()['SomeModel'] but of course that's extremely ugly.

The best alternative would be using a type annotation, ie model: SomeModel instead of model = SomeModel. Those only trigger reification of the import when getting the type hints of the object.

Ngôn ngữ chính
Python
Star
580
Fork
105
Merge trung bình
9 giờ 8 phút
Pull request đã merge (30 ngày)
3

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của marshmallow-code/marshmallow-sqlalchemy

Tất cả issue của marshmallow-code/marshmallow-sqlalchemy

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.