16

I use pyscripter for coding, it supports auto-completion. So, when I say:

a = []
a.

It gives me all the list functions. similarly with strings I do b=''.

But for the file type, I have to use file. and choose the function and write its arguments and then replace file with the variable name.

Is there a way to declare a variable type explicitly in Python, so that my IDE can be more useful?

orftz
  • 1,138
  • 13
  • 22
lalli
  • 6,083
  • 7
  • 42
  • 55
  • 14
    Writing bad Python code just to please an IDE doesn't sound like such a great idea to me... – Tim Pietzcker Oct 28 '10 at 10:08
  • 2
    once you've used `a.your_attribute` in your code, pyDev-eclipse will keep showing that attribute after pressing . in list with CTRL + SPACE, with its intelligence !!! – shahjapan Oct 28 '10 at 10:11
  • If you have to make your IDE absolutely useful, you will have to morph python into java .. including specifying the type explicitly. – pyfunc Oct 28 '10 at 10:43
  • 9
    I'm currently switching from C#/Java to Python and the dynamic types seem to create a lot more problems than they solve. They just feel messy and a step backwards. – Damien Jan 16 '13 at 23:26
  • Most decent Python IDEs automatically show possible methods on an object when you type *obj.* : Eclipse, spyder, Wing, Canopy... – smci Jun 21 '13 at 22:52
  • Possible duplicate of [how to declare variable type, C style in python](https://stackoverflow.com/questions/3933197/how-to-declare-variable-type-c-style-in-python) – Cam T Jan 29 '19 at 00:11

3 Answers3

15

As of Python 3, you can explicitly declare variables by type:

x: int = 3

or:

def f(x: int):
    return x
escofresco
  • 161
  • 1
  • 4
  • Will a warning or Exception be raised if I assign a string to it after explicitly declaring as an `int`? – NameError Mar 22 '22 at 14:52
10

Python has no type declarations. Python 3 introduces something called function annotations, which Guido sometimes refers to as "the thing that isn't type declarations," because the most obvious use of it will be to provide type information as a hint.

As others have mentioned, various IDEs do a better or worse job at auto-completing.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
4

in case you want methods callable on a type ...you can always use dir(var) in python console...

mossplix
  • 3,783
  • 2
  • 26
  • 31
  • +1 I think that this is the right answer. Learn the methods available on it the hard way and quit your bellyaching. – aaronasterling Oct 28 '10 at 12:37
  • 2
    @aaronasterling How silly. "Work harder than you have to simply because languages like Python and Javascript make things more difficult than they have to be." – GrowingCode247 Jun 10 '20 at 22:22