2017-11-20 11 views
0

アプリケーションでmypyのテストを開始しましたが、instances of classで作業しようとすると成功しません。Mypy:インスタンスのリスト?呼び出し可能?

ButtonGenerator.__new__BaseButtonURLButton)のリストまたは単にBaseButtonURLButton)インスタンスを受け入れるべきです。私もCallableの一覧を試みた print(ButtonGenerator(URLButton('https://stackoverflow.com')))

buttons.py

class BaseButton(object): 
    def __init__(self): 
     pass  

class ButtonGenerator(BaseButton): 
    def __new__(self, buttons: Union[List[BaseButton], BaseButton]) -> Union[List[Dict[str, str]], Dict[str, str]]: 
     if (isinstance(buttons, list)): 
      if (not all(isinstance(button, BaseButton) for button in buttons)): 
       raise ValueError('Invalid Buttons instances.') 

      return [button.button_dict for button in buttons] 

     return buttons.button_dict 


class URLButton(BaseButton): 
    def __init__(self, url, title=None): 
     self.button_dict = { 
      'type': 'web_url', 
      'url': url 
     } 

     if (title): 
      self.button_dict['title'] = title 

エラー

messenger/buttons.py:17: error: "BaseButton" has no attribute "button_dict" 
messenger/buttons.py:19: error: "BaseButton" has no attribute "button_dict" 

例。それはその暗黙の型以外を返すようにしようとした場合

答えて

0

mypyは現在__new__を尊重しない:https://github.com/python/mypy/issues/1020

解決策ではなく、機能または静的/クラスメソッドを使用することです。あなたの場合、私はであると考えています__new__はクラスをすべて返していないので、BaseButtonのサブクラスに従うと、これは一般的に悩まされているので、クラスコンストラクタよりも直観的です。誰かがクラスをインスタンス化すると、辞書やリストではなく、クラスインスタンスを取得することを期待します。

関連する問題