これはPythonスタイルの質問です。私のPythonコードは機能します。コードを読みやすく、理解しやすく、デバッグしやすくするためのコーディング規約の提案を探しています。
具体的には、呼び出し元がカスタムGUIにウィジェットを追加できるようにするPythonクラスに取り組んでいます。GUIを設定するには、ユーザーはウィジェット(名前付きまたは匿名)をウィジェット領域に追加して、ウィジェットがツリーを形成するようにするメソッドを作成します(GUIで一般的です)。
ユーザーがすべてのコンテナウィジェットに名前を付けることなくウィジェットのツリーを設定できるようにするため(そして、子ウィジェットが追加されるたびにその親ウィジェットを明示的に参照するため)、私のAPIは「親ウィジェット」の概念をサポートしています。スタック"。コンテナウィジェットを宣言するとき、ユーザーはそのウィジェットをこのスタックにプッシュするように指定できます。その後、デフォルトで、スタックの一番上にある親にさらにウィジェット(親を明示的に指定しない)が追加されます。これが私が意味することの簡単な例です:
def SetupGUI(self):
self.AddWidget(name="root", type="container", push=True)
self.AddWidget(type="container", push=True)
for i in range(0,8):
self.AddWidget(name="button%i"%i, type="button")
self.PopParentWidget() # pop the buttons-container off the parents-stack
self.AddWidget(type="container", push=True)
for i in range(0,8):
self.AddWidget(name="slider%i"%i, type="slider")
self.PopParentWidget() # pop the sliders-container off the parents-stack
self.PopParentWidget() # pop the container "root" off the parents-stack
これは便利ですが、GUI階層がより複雑になると、self.PopParentWidget()のどの呼び出しがどのコンテナーウィジェットに対応するかを判断するのが難しくなり始めます。1つが多すぎたり少なすぎたりするのは簡単で、GUIで非常に面白いが意図しない結果になってしまいます。
だから私の質問は、PopParentWidget()に明示的なウィジェット名を強制することを除いて(すべてのコンテナウィジェットに名前を付ける必要がないので避けたい)、push/を作成するためにできることはありますか?コード内のポップペアリングは、目に見えますか?
C / C ++ではインデントを使用してそれを行いますが、Pythonではそれを行うことは許可されていません。たとえば、私はこれができるようになりたいです:
def SetupGUI(self):
self.AddWidget(name="root", type="container", push=True)
self.AddWidget(type="container", push=True)
for i in range(0,8):
self.AddWidget(name="button%i"%i, type="button")
self.PopParentWidget() # pop the buttons-container off the parents-stack
self.AddWidget(type="container", push=True)
for i in range(0,8):
self.AddWidget(name="slider%i"%i, type="slider")
self.PopParentWidget() # pop the sliders-container off the parents-stack
self.PopParentWidget() # pop the container "root" off the parents-stack
...しかし、私がそのように創造的になると、PythonはIndentationErrorをスローします。