gpt4 book ai didi

python - PyCharm - matplotlib(和其他导入模块)的自动完成

转载 作者:太空狗 更新时间:2023-10-30 01:06:30 25 4
gpt4 key购买 nike

我在 Windows 10 上使用 PyCharm 2016.1 和 Python 2.7,并导入了 matplotlib 模块。

由于 matplotlib 模块非常广泛,而且我是 Python 的新手,我希望 PyCharm 中的自动完成功能可以帮助我了解对象的现有属性/功能。每次都翻看 api 文档,不知道要找什么,去哪里找,这样会更方便。

例如:

from matplotlib import pyplot as plt
fig, ax = plt.subplots()

当我键入 ax. 时,轴的属性、函数等没有自动完成,我只得到建议列表。

我已经试过了 this并直接导入轴模块:

import matplotlib.axis as axis

from matplotlib.axis import Axis as axis

智能自动完成和“收集运行时类型信息”已启用。

是否有一种方法可以像描述的那样启用自动完成功能,或者是否有其他支持该功能的 IDE?

最佳答案

我相信您的问题在这里突出显示:

https://intellij-support.jetbrains.com/hc/en-us/community/posts/205816499-Improving-collecting-run-time-type-information-for-code-insight?sort_by=votes

Tldr 返回类型可能会有所不同,因此无法在编译时计算出来。

最被接受的方法是使用类型提示,因为它只能在运行时确定它是什么类型:

import matplotlib.axes._axes as axes

fig = plt.figure(figsize=(5,10))
ax1 = fig.add_subplot(3,1,1) # type:axes.Axes
ax1.set_xlabel('Test') <- now autocompletes

您还可以尝试一个assert isinstance:

import matplotlib.axes._axes as axes

fig = plt.figure(figsize=(5,10))
ax1 = fig.add_subplot(3,1,1)
assert isinstance(ax1, axes.Axes)
ax1.set_xlabel('Test')

如果你按照你正在寻找的方法执行它,它不会找到自动完成:

ax1.set_xlabel('Test')
assert isinstance(ax1, axes.Axes)

有了这个,你不应该让 isinstance 决定你代码的控制流,如果你试图运行一个对象上不存在的方法,它应该崩溃,但是,如果你的不同对象有一个同名的方法(!)那么你无意中达到了那个目标而没有注释。所以我更喜欢它,因为你希望它早点崩溃并在正确的地方崩溃。 YMMV

来自文档:

Assertions should not be used to test for failure cases that canoccur because of bad user input or operating system/environmentfailures, such as a file not being found. Instead, you should raise anexception, or print an error message, or whatever is appropriate. Oneimportant reason why assertions should only be used for self-tests ofthe program is that assertions can be disabled at compile time.

If Python is started with the -O option, then assertions will bestripped out and not evaluated. So if code uses assertions heavily,but is performance-critical, then there is a system for turning themoff in release builds. (But don't do this unless it's reallynecessary.

https://wiki.python.org/moin/UsingAssertionsEffectively

或者,如果您不想以这种方式添加到您的代码中,并且通过 anoconda 安装了 Ipython/jupyter,您可以通过右键单击要运行的代码并选择“执行选择”从控制台获得代码完成控制台”

关于python - PyCharm - matplotlib(和其他导入模块)的自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36936555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com