3

Is there a way to help PyDev code completion by telling it the type of a variable?

With PDT, you can use PHPDoc-like syntax for such purpose:

/* @var $my_var MyClass */
$my_var = myFunction();
// PDT is able to figure out that $my_var is a MyClass object.

But till now, I cannot figure out how to do the same in python.

Benoît Vidis
  • 3,908
  • 2
  • 23
  • 24
  • possible duplicate of [Pydev Code Completion for everything](http://stackoverflow.com/questions/6218778/pydev-code-completion-for-everything) – Duncan Jones Sep 01 '14 at 12:42

3 Answers3

3

Actually, you can if you do an assert isinstance()

E.g.:

a = function()
assert isinstance(a, MyClass)
a. <- would get the proper completions

Note that Pydev does analyze the return of the functions, so, it's possible that it knows that on a number of cases.

Also, that shouldn't have runtime penalties if you use python -O (which will remove the asserts)

Fabio Zadrozny
  • 24,814
  • 4
  • 66
  • 78
3

The assert trick does not seem to work for me with PyDev 2.2.2 ; it is still supposed to ?

However another trick I tried and that work is the following :

class Foo(object):
    def __init__(self, bar):
       self.bar = bar
       # Tricking PyDev
       if (not self.bar):
          self.bar = Bar()
          raise Exception("Bar should not be null")

In all cases, it looks pretty hacky, and I would love a cleaner way to do things (documentation, annotation, whatever)

phtrivier
  • 13,047
  • 6
  • 48
  • 79
  • Thanks for sharing this method -- worked well for me too (PyDev v2.5). `assert isinstance` is only working within the same method; it doesn't seem to propagate the type into the instance variables. – Justin May 17 '12 at 12:42
1

Nope (see the docs). It looks like PyDev does completion of imported stuff and language keywords.

It doesn't seem like this would come up a lot though. The variable in question seems like it would only be unknown to pydev if it were passed in as a function argument with no default value.And, if you have a function operating on your own class, it seems like that should be a class member (so autocomplete would already work).

Seth
  • 45,033
  • 10
  • 85
  • 120
  • I'm not sure why you say it would not come up a lot. As you said, any time you pass a variable to a method, PyDev has no way of guessing its type unless it has a default value - but I would say that methods with default params are very rare compared to methods without, aren't they ? – phtrivier Sep 16 '11 at 09:24