LoginSignup
105
104

More than 5 years have passed since last update.

PyCharm での type hinting を使いこなす

Posted at

PyCharm を使うと、 docstring のコメントを元に型推論してくれます。

def foo(x):
    """
    :rtype: list of str
    """
    return x

def bar(x):
    a = foo(x)
    a[0].  # <- この時点で文字列のメソッドが候補になる

docstring

Sphinx の書き方と Epytext の書き方を受け付けるようですが、 Python では Sphinx の方が一般的なのでそれに習いましょう。

def repeat(x, y):
    """
    :param str x: value to repeat
    :type  y: int
    :param y: number of repeat
    :rtype:   str
    :return:  repeated string
    """
    return x * y

引数は :param 型 名前: という書き方でもいいですし、 :type 引数名: 型 という書き方もできます。
戻り値は :rtype: で書きましょう。

型宣言

StdlibTypes2.properties というファイルをみると書き方が大体わかります。このファイルは Mac だと /Applications/PyCharm 2.7.2 EAP.app/helpers というディレクトリにあります。

いくつか抜粋してみます。

__builtin__.locals = \
  :rtype: dict of (string, unknown)

__builtin__.filter = \
  :type function_or_none: collections.Callable or None \n\
  :type sequence: collections.Iterable of T \n\
  :rtype: list of T \n\

__builtin__.enumerate.__init__ = \
  :type iterable: collections.Iterable of T \n\
  :type start: int or long \n\
  :rtype: enumerate of (int, T) \n\

__builtin__.enumerate.next = \
  :rtype: (int, T) \n\

__builtin__.dict.__init__ = \
  :type seq: collections.Iterable of (T, V) \n\
  :rtype: dict of (T, V) \n\

__builtin__.dict.__getitem__ = \
  :type y: T \n\
  :rtype: V \n\

__builtin__.dict.items = \
  :rtype: list of (T, V) \n\

複合型は、タプルの場合のみ (int, str) のような書き方ができて、それ以外の場合は dict of (T, V) のように of を使って表すようです。

型引数は T だけじゃなくて任意の大文字一文字が使えそうです。

一般的な型を返す時は collections にある ABC を of T の形で使えばよさそうです。

複数の方を受け取れる場合は、 int or None の用に or でつなげるようです。

その他の変数への type hinting

#: :type: int
x = unknown()

のようにコメントをつけると hinting できます。でも、

#: ????
a, b = unknwon()

この場合にどうやって hinting すればいいのかまだ判りません。
一回タプルで受け取ることもできますが、不恰好なので、関数側にちゃんと :rtype: を定義するのがよさそうです。

105
104
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
105
104