1

我惊喜地发现带有 PyDev 的 Eclipse 能够猜测大多数变量的类型并帮助显示成员列表。我正在学习 Python,我认为我应该忘记强类型语言的所有优点,但看起来我错了。

我想知道 IDE(甚至 Python 解释器)能走多远。我在下面的代码段中定义了一些模块级变量,我希望 IDE 知道它们的类型。

关于 IDE 的问题 1:是否可以声明变量的类型以便代码完成知道其成员?

关于 Python 的问题 2:是否可以声明变量的类型,以便在执行期间更改类型时收到警告?

例如,将光标c.放在以下代码段上的第一个之后并按下ctrl+space,第一个建议是val. 耶!

Python 变量是动态的,它们的类型可以改变,而这个技巧在第二种情况下不起作用,c.因为 Eclipse 无法知道c在模块级别定义并使用 infunc2将在func1.

c = None

class MyClass:
    val = 0

def func1():
    c = MyClass()
    print c. # Eclipse knows that val is a member of c 

def func2():
    print c. # Eclipse doesn't know that val is a member of c
4

3 回答 3

4
def something(c):
    #eclipse does not know what c is
    assert isinstance(c,MyClass)
    #now eclipse knows that c is an instance of MyClass
    c. #autocomplete
于 2013-08-26T17:22:10.790 回答
2

尽管 assert isinstance() 确实有效,但 PyDev 2.8 添加了一种无需断言即可添加该信息的方法,只需通过正确记录您的代码(使用 sphinx 或 epydoc 文档字符串)。

有关如何正确记录代码以使其接受类型声明的详细信息,请参见:http ://pydev.org/manual_adv_type_hints.html。

于 2013-09-06T17:19:47.683 回答
1

如果你使用decorators你的 IDE 可能会意识到你在做什么:

@accepts(MyClass)   #Let python and the interpreter know
def foo(bar):       #You're only accepting MyClass isntances
    bar.            #Should autocomplete
于 2013-08-26T17:53:18.470 回答