Explicitly declaring a variable type in Python
Asked Answered
D

3

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?

Downcast answered 28/10, 2010 at 10:6 Comment(6)
Writing bad Python code just to please an IDE doesn't sound like such a great idea to me...Rabaul
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 !!!Quasijudicial
If you have to make your IDE absolutely useful, you will have to morph python into java .. including specifying the type explicitly.Perjured
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.Agosto
Most decent Python IDEs automatically show possible methods on an object when you type obj. : Eclipse, spyder, Wing, Canopy...Imogene
Possible duplicate of how to declare variable type, C style in pythonChinese
N
4

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

Nolen answered 28/10, 2010 at 12:12 Comment(2)
+1 I think that this is the right answer. Learn the methods available on it the hard way and quit your bellyaching.Antipathetic
@Antipathetic How silly. "Work harder than you have to simply because languages like Python and Javascript make things more difficult than they have to be."Radon
R
15

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

x: int = 3

or:

def f(x: int):
    return x
Reset answered 19/10, 2019 at 16:7 Comment(1)
Will a warning or Exception be raised if I assign a string to it after explicitly declaring as an int?Callista
E
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.

Edge answered 28/10, 2010 at 10:57 Comment(0)
N
4

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

Nolen answered 28/10, 2010 at 12:12 Comment(2)
+1 I think that this is the right answer. Learn the methods available on it the hard way and quit your bellyaching.Antipathetic
@Antipathetic How silly. "Work harder than you have to simply because languages like Python and Javascript make things more difficult than they have to be."Radon

© 2022 - 2024 — McMap. All rights reserved.