0

Sublime Text 2 用の小さなプラグインを作成しています。ワークフローでは、一連の回答を得るためにユーザーに複数回プロンプトを表示する必要があります。

入力を取得するために show_input_panel を使用しており、各回答を収集する関数を定義しています。

コードのサンプルを次に示します。

import sublime, sublime_plugin

class SampleCommand(sublime_plugin.TextCommand):

    #############################
    # Main
    #############################

    def run(self, edit):
        self.edit = edit

        self.window = sublime.active_window()

        # first prompt
        self.window.show_input_panel('First question', '', self.on_first_answer, None, None)

    #############################
    # Async Handlers
    #############################

    def on_first_answer(self, answer_a):
        self.answer_a = answer_a
        self.window.show_input_panel('Second question', '', self.on_second_answer, None, None)

    def on_second_answer(self, answer_b):
        self.answer_b = answer_b
        self.window.show_input_panel('Third question', '', self.on_third_answer, None, None)

    def on_third_answer(self, answer_c):
        answers = self.answer_a + self.answer_b + answer_c
        sublime.message_dialog('Your answers: ' + answers)

私は Python を初めて使用するので、これらの複数のコールバックを整理するためのより良い方法があるかどうか疑問に思っていました。

JavaScript では、匿名クロージャーを使い始めました。これにより、各回答をオブジェクトに保存する必要がなくなりました。クロージャが十分でない場合は、promise のようなものを試します。

Python でそのようなシナリオを管理する最善の方法は何ですか?

4

1 に答える 1

2

generator.send次のような場合に非常に便利です。

import sublime

def prompt_sequence(g):
    def progress(result):
        try:
            progress.caption, progress.initial_text = g.send(result)
            sublime.active_window().show_input_panel(
                progress.caption,
                progress.initial_text,
                progress, None, None
            )
        except StopIteration:
            pass

    progress(None)

def foo():
    first_answer = yield ('First question', '')
    second_answer = yield ('Second question', '')
    third_answer = yield ('Thirdquestion', '')

    sublime.message_dialog('Your answers: ' + answers)

prompt_sequence(foo())

または別の方法で書かれています(機能しない場合があります):

def self_referencing(gen_func):
    @functools.wraps(gen_func)
    def wrapped(*args, **kwargs):
        g = gen_func(lambda: g, *args, **kwargs)
        return g
    return wrapped



class SampleCommand(sublime_plugin.TextCommand):
    @self_referencing
    def get_things(gen_self, self):
        sublime.active_window().show_input_panel(
            'First question', '',
            gen_self().send, None, None
        )
        result_a = yield
        sublime.active_window().show_input_panel(
            'Second question', '',
            gen_self().send, None, None
        )
        result_b = yield
        sublime.active_window().show_input_panel(
            'Third question', '',
            gen_self().send, None, None
        )
        result_c = yield
于 2013-07-06T22:12:55.983 に答える