Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tools for Visual Studio - tell the IDE what type a parameter will be

I just started using Visual Studio 2015, and I really like it, especially the code completion features. Right now I'm writing some simple Python code to draw an object on a Tkinter Canvas:

    def draw(self, can):
        """ can is a Tkinter canvas on which this node will draw itself. """
        can.<something>

This being Python, nowhere in the actual code is it indicated that "can" is going to be a Canvas, so VS can't autocomplete or suggest anything after I type "can." Is there a way I can tell Visual Studio that can will be of type tkinter.Canvas?

like image 928
Axesilo Avatar asked Mar 12 '23 11:03

Axesilo


2 Answers

Yes, you can use an assertion statement. This will trigger VS autocomplete settings. It's not the most beautiful way to do it, but I think right now that's the best option.

assert isinstance(can, tkinter.Canvas)

Take a look at this answer for more.

like image 151
RatherBKnitting Avatar answered May 01 '23 04:05

RatherBKnitting


I'm going to preface this by saying I haven't used Python Tools for Visual Studio (although I use Visual Studio for C# and it's a great IDE) and so this isn't a direct answer for your question. However, I'm guessing from "I just started using Visual Studio 2015" that you might be checking out different tools, so maybe this can still be helpful to you.

I started using PyCharm a few days ago since I plan on doing some serious Python work soon, and I have to say it's pretty phenomenal in my opinion.

To relate back to your question, you have at least a couple ways of letting PyCharm infer the type of your parameters.

Method 1: Python 3 Type Hints

If you're using a Python 3.5 interpreter, you can help PyCharm infer the types of parameters by providing type hints in your code.

enter image description here

Method 2: Docstrings

Alternatively, you can let PyCharm infer types by providing a docstring with the function that contains type information. In the example below, I'm using documentation in reStructuredText format.

The advantage of doing it this way is that it works whichever interpreter you're using.

enter image description here

like image 33
Tagc Avatar answered May 01 '23 03:05

Tagc