Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: tell my IDE what type an object is

When I write a function in Python (v2.7), I very often have a type in mind for one of the arguments. I'm working with the unbelievably brilliant pandas library at the movemement, so my arguments are often 'intended' to be pandas.DataFrames.

In my favorite IDE (Spyder), when you type a period . a list of methods appear. Also, when you type the opening parenthesis of a method, the docstring appears in a little window.

But for these things to work, the IDE has to know what type a variable is. But of course, it never does. Am I missing something obvious about how to write Pythonic code (I've read Python Is Not Java but it doesn't mention this IDE autocomplete issue.

Any thoughts?

like image 924
LondonRob Avatar asked Jan 22 '14 15:01

LondonRob


People also ask

How do you check the type of an object in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

Do Python objects have a type?

Objects behave differently from one another according to what “type” a given object is. We reviewed several fundamental object types in Python: int , float , complex : the numerical types. bool : the boolean type.

Which function is used to determine the type of an object in Python?

type() returns the type of an object. You can use this to get and print the type of a variable and a literal like typeof in other programming languages. The return value of type() is type object such as str or int .


2 Answers

I don't know if it works in Spyder, but many completion engines (e.g. Jedi) also support assertions to tell them what type a variable is. For example:

def foo(param):
    assert isinstance(param, str)
    # now param will be considered a str
    param.|capitalize
           center
           count
           decode
           ...
like image 174
jdm Avatar answered Sep 17 '22 15:09

jdm


Actually I use IntelliJ idea ( aka pyCharm ) and they offer multiple ways to specify variable types:

1. Specify Simple Variable

Very simple: Just add a comment with the type information behind the definition. From now on Pycharm supports autcompletition! e.g.:

def route():
    json = request.get_json() # type: dict

Source: https://www.jetbrains.com/help/pycharm/type-hinting-in-pycharm.html

2. Specify Parameter:

Add three quote signs after the beginning of a method and the idea will autocomplete a docstring, as in the following example:

example of method parameters

Source: https://www.jetbrains.com/help/pycharm/using-docstrings-to-specify-types.html

(Currently on my mobile, going to make it pretty later)

like image 41
Simon Fakir Avatar answered Sep 17 '22 15:09

Simon Fakir