stenci
stenci

Reputation: 8501

How to tell the Python IDE (and interpreter) the type of a variable

I was pleasantly surprised to find out that Eclipse with PyDev is able to guess the type of most variables and helps showing the list of the members. I'm learning Python, and I thought that I should forget about all the advantages of strongly typed languages, but it looks like I was wrong.

I would like to know how far the IDE (or even the Python interpreter) goes. I have a few module level variables defined as in the snippet below, and I would like for the IDE to know their type.

Question 1 about the IDE: Is it possible to declare the type of a variable so that the code completion knows about its members?

Question 2 about Python: Is it possible to declare the type of a variable so that I get a warning if the type is changed during the execution?

For example placing the cursor after the first c. on the following snippet and pressing ctrl+space, the first suggestion is val. Yay!

Python variables are dynamic, their type can change, and this trick doesn't work on the second c. because there is no way for Eclipse to know that the c defined at module level and used in func2 is going to be defined in 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

Upvotes: 1

Views: 910

Answers (3)

Fabio Zadrozny
Fabio Zadrozny

Reputation: 25372

Although the assert isinstance() does work, PyDev 2.8 added a way of adding that information without the assert, just through documenting your code properly (using sphinx or epydoc docstrings).

See: http://pydev.org/manual_adv_type_hints.html for details on how to document the code properly for it to accept the type declarations.

Upvotes: 2

scohe001
scohe001

Reputation: 15446

If you use decorators your IDE will probably realize what you're doing:

@accepts(MyClass)   #Let python and the interpreter know
def foo(bar):       #You're only accepting MyClass isntances
    bar.            #Should autocomplete

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 114098

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

Upvotes: 4

Related Questions