LoginSignup
7
1

More than 1 year has passed since last update.

【Tensorflow】VSCodeのPylanceコード補完がTensorflowのKerasに効かない【VSCode】

Last updated at Posted at 2021-12-14

2022/3/12追記

下記WorkAroundがうまく行かない場合があります。
僕の環境でもなんか気づいたらうまくいかなくなってました。2.7とかそのへんからかもしれません。
その場合は

from keras.api._v2 import keras

とするとうまく回避できます。
見た目が気持ち悪いのでうまくpylanceに適合できるようにTensorflow側にPRが立っています。
進行中の議論の内容はTensorflowのIssueでご確認ください。

KerasがTensorflowから独立したらしい

Keras been split into a separate PIP package (keras), and its code has been moved to the GitHub repositorykeras-team/keras. The API endpoints for tf.keras stay unchanged, but are now backed by the keras PIP package. The existing code in tensorflow/python/keras is a staled copy and will be removed in future release (2.7). Please remove any imports to tensorflow.python.keras and replace them with public tf.keras API instead.

Tensorflow Release Note Version 2.6.0

こうしたいろいろの関係があって内部処理ではTensorflowはKerasをLazyにLoadすることにしました。
これはPylanceなどによる静的型チェックの対象外です。

その結果VSCodeにPython/Pylance拡張を入れてもコード補完などのサポートが受けられなくなってしまうのでした。

Solution: tf.kerasにimport文をかける

# pylance works!
import tensorflow.keras as keras
layer = keras.layers.Dense(128)

# pylance does not work!
import tensorflow as tf
layer = tf.keras.layers.Dense(128)

Screenshot from 2021-12-14 22-25-39.png
Screenshot from 2021-12-14 22-26-54.png

LazyLoaderによってロードされたkerasモジュールをPylanceに解析させるにはimport文をtensorflow.kerasに対して実行する必要があります。

そうするとLazyLoaderが処理されてPylanceは今まで通りのkerasモジュールと解釈してくれるようになるのでした。

最後に

最近PythonでもTypeScriptでもTypeHintingアツい!PylanceによるCode補完を使うとVSCodeの画面がカラフルになって楽しい!
LazyLoaderをやっつけてよいTypeHintingライフを〜

それでは最後にLGTMとフォローも忘れずにお願いします!

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