Skip to main content

Classic Scenarios

Предоставляет примитивы для написания простых сценариев с бизнес-логикой.

Установка

pip install classic-scenarios

Использование

from classic.components import component, no_init
from classic.scenarios import scenario, Return

import pydantic


class SomeEntity(pydantic.BaseModel):
    """Это как будто очень полезный класс,
    представляющий собой какое-то понятие из предметной области
    """
    id: int
    

class SomeParams(pydantic.BaseModel):
    """Модель для проверки ввода"""
    some_obj_id: int
    some_prop: str

    
class Database:
    """Интерфейс для объекта, работающего с БД"""
    
    def get(self, id):
        raise NotImplemented
    
    def save(self, obj):
        raise NotImplemented

    
# Использование component не обязательно, 
# но с ним выглядит более идиоматично
@component
class SomeUseCase:
    db: Database
    
    params: SomeParams = no_init(None)
    some_obj: SomeEntity = no_init(None)
    
    @scenario
    def run(self):
        """
        Это сценарий транзакции,
        в котором последовательно,
        шаг за шагом прописаны шаги.
        """
        self._do_something()
        self._do_anything()
        self._and_something_yet()
    
    def _do_something(self):
        """Здесь можно сделать что-то полезное, например, взять объект из БД"""
        self.some_obj = self.db.get(self.params.some_obj_id)
    
    def _do_anything(self):
        if self.some_obj is None:
            # Это приведет к остановке сценария, 
            # но сценарий не упадет, а вернет 'No obj'
            raise Return('No obj')
        
        self.some_prop = 'Some value'

    def _and_something_yet(self):
        self.db.save(self.some_obj)


use_case = SomeUseCase(Database())
use_case.run(params=SomeParams(123))

При вызове run декоратор scenario сделает 2 вещи:

  • скопирует полученный в self инстанс SomeUseCase, чтобы продолжить исполнение уже с копией. Это нужно для потокобезопасности.
  • разложит все полученные kwargs в self. В примере выше объект SomeParams, переданный в ключе params, будет доступен в сценарии в атрибуте self.params.

Копирование объекта имеет один побочный эффект. Из-за того, что при вызове run снимается поверхностная копия объекта, копия получит ссылки на те же объекты. Если в свойствах класса-сценария будут инстансы изменяемых типов, то при повторном вызове сценария мы увидим состояние из предыдущего!

Это похоже на эффект, получаемый при использовании инстансов сложных типов в качестве аргументов функции по умолчанию:

def func(arg=[]):
    arg.append('1')

Здесь так же между вызовами будет сохраняться состояние arg. В целом, если такое свойство испольpуется только для чтения, в этом нет проблем. Кроме того, сложно представить себе такое свойство, которое имело бы свойство по умолчанию, то есть инициализировалось бы конструктором, и при этом было бы изменяемо, потому такое поведение не кажется проблемой.

Metadata

Release files for classic-scenarios 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for classic-scenarios 0.2.0
File Size Uploaded Provenance
classic_scenarios-0.2.0.tar.gz 5.6 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for classic-scenarios 0.2.0
File Interpreter ABI Platform
classic_scenarios-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 11.5 kB

Release files / classic_scenarios-0.2.0.tar.gz

Download URL classic_scenarios-0.2.0.tar.gz
Size 5.6 kB
Tags Source
SHA-256 checksum
How to use checksums
71c651c5e4813e064b7173197516c13c87442fb80b041132b0463f109abc5fe3
BLAKE2b-256 checksum
How to use checksums
972bc0f476c83b67485f73950242638258ebde751f8e903de0cfd4ad3231fc35
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 8, 2026.

Transparency log

Release files / classic_scenarios-0.2.0-py3-none-any.whl

Download URL classic_scenarios-0.2.0-py3-none-any.whl
Size 5.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
300872f9227c4ef3e34c587f35bb17ec1809131aa3931069a82c986dc38a13cf
BLAKE2b-256 checksum
How to use checksums
55562a0db7310a75989c4ffc46f17b68966eff1bee5075ff369d0cf1f927df5c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 8, 2026.

Transparency log

Security for classic-scenarios 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for classic_scenarios-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 8, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page