LoginSignup
1
0

More than 5 years have passed since last update.

Python 2.7の class変数で PyCharmのコード補完(Type Hints?)を可能にする

Last updated at Posted at 2018-08-12

PyCharm でclassの変数にコード補完をさせたい。百聞は一見にしかず。

コード補完が効かない書き方

no_type_hint.py
import redis

class MyRedis(object):
  def __init__(self):
    self.client = None

  def connect(self):
    self.client = redis.StrictRedis()

# 以下を入力してもコード補完されない
MyRedis().client.

スクリーンショット 2018-08-12 23.22.58.png

コード補完を効かせる書き方

type_hint.py
import redis

class MyRedis(object):
  def __init__(self, client=None):
    # type: (redis.StrictRedis) -> None  # ←ポイント
    self.client = client

  def connect(self):
    self.client = redis.StrictRedis()

# 以下client後のピリオドを入力すると、 `redis.StrictClient` のコード補完が行われる
MyRedis().client.

スクリーンショット 2018-08-12 23.23.34.png
redis.StrictRedis のメソッドである incr(..) などが補完候補されていることが確認できる

動作確認

  • PyCharm 2018.2 CE

いいわけ

Type HintsPEP 484 について、著者は正しく理解しているわけではないです。実績ベースの できた! を本記事にて共有させてください。

参考文献

1
0
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
1
0