Saturday, January 8, 2011

PyCharm autocompletion

I have not yet figured out how it works and to what extent. In fact I have used it just for one file projects, so I don't really know whether it works across file boundaries. But look at this:



Fairly impressive, huh? There are no user provided type hints. Unfortunately enough, it does not look like the x = f(B()) statement is taken into account: simply the IDE guesses that since I have a class named B a parameter named b may be an instance of b and suggests B.bar as a possible completion. Ok, this is possibly overly optimistic, however, in my experience I've found quite often that this is useful (at least, better than nothing).

In the following screen-shot, I demonstrate how the good old assert isinstance trick we used in WingIDE still works:



Still, I'm not extremely happy with this strategy as it mimics too much static typing. In fact if I wanted to specify types for my parameters, I'd use Java. No doubt that writing

bool f(B x) { }

is faster than:

def f(x):
    assert isinstance(x, B)

I admit... I don't really like the trick. However, sometimes it is not overly restrictive do such typechecking: e.g., numbers are expected to inherit from the proper abstract base classes and when using libraries such as numpy, it is rather safe to assume that some parameters are numpy arrays.

The point where this strategy fails blatantly is with return types. Having to add type assertions to function return types is horrible, basically infeasible. Here Pycharm is smart and relies on a convention from the standard library, consider for example:

vars(...)
    vars([object]) -> dictionary

    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.

We can see that here we somewhat suggest (in the documentation) the return type of the function. Well, since they implemented that for standard library code, they are letting developers using it as well. PyCharm developers also promised to add similar conventions based on other standards (e.g., Sphynx)



Unfortunately the types of the input parameters are not considered.



2 comments:

Amin's Weblog said...

Hi.

This may help:

http://stackoverflow.com/questions/6318814/how-can-i-tell-pycharm-what-type-a-parameter-is-expected-to-be

Regards,
Amin

Unknown said...

Excellent. But this is rather new... back then there was no such possibility.

I think this is really good. I do not to limit the executable with assert (which means that a person that behaves like a person but is not a Person breaks the code), but still get the autocompletion features. Afterall, if I expect something which behaves like a Person, it is ok to have the IDE complete Person's methods.

Ok, __getattr__ breaks this, but of course there is nothing that can be done to avoid that.