我惊喜地发现带有PyDev的Eclipse能够猜出大多数变量的类型并帮助显示成员列表。我正在学习Python,我认为我应该忘记强类型语言的所有优点,但看起来我错了。
我想知道IDE(甚至Python解释器)的用途。我在下面的代码段中定义了一些模块级变量,我希望IDE知道它们的类型。
关于IDE的问题1:是否可以声明变量的类型以便代码完成知道其成员?
关于Python的问题2:是否可以声明变量的类型,以便在执行期间更改类型时会收到警告?
例如,将光标放在第一个c.
后面的以下代码段并按ctrl+space
,第一个建议是val
。耶!
Python变量是动态的,它们的类型可以改变,而这个技巧在第二个c.
上不起作用,因为Eclipse无法知道在模块级定义的c
并使用func2
中的定义将在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
答案 0 :(得分: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
答案 1 :(得分:2)
尽管断言isinstance()确实有效,但PyDev 2.8添加了一种在没有断言的情况下添加该信息的方法,只需通过正确记录代码(使用sphinx或epydoc docstrings)。
有关如何正确记录代码以接受类型声明的详细信息,请参阅:http://pydev.org/manual_adv_type_hints.html。
答案 2 :(得分:1)
如果您使用decorators
,您的IDE可能会意识到您正在做的事情:
@accepts(MyClass) #Let python and the interpreter know
def foo(bar): #You're only accepting MyClass isntances
bar. #Should autocomplete