Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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 について、著者は正しく理解しているわけではないです。実績ベースの できた! を本記事にて共有させてください。

参考文献

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした