Alisa Kunapinun
Alisa Kunapinun

Reputation: 63

Python list type declaration

I tried to set variable types in my functions. There is no problem when I tried to use normal variable type. For example,

def myString(name:str) -> str:
    return "hello " + name

However, I got problem in list. Many examples in internet said use List, but it got error. Now I use list, and there is no error. Is it ok to use this?

Another problem that I found someone can use

def myListString() -> list[str]:
    return ["ABC", "CDE"]

I found error.

TypeError: 'type' object is not subscriptable

How should I correct this?

Another problem that I found is I cannot declare myClass in the myClass. For example,

class Point:
    def __init__(self, x:int, y:int):
        self.x:int = x
        self.y:int = y

    def isSamePoint(self, p:Point) -> bool:
        return ((self.x==p.x) and (self.y==p.y))
p0 = Point(10, 5)
p1 = Point(5, 5)
p0.isSamePoint(p1)

I found error,

def isSamePoint(self, p:Point):
NameError: name 'Point' is not defined

Please help me solve the problem.

Upvotes: 6

Views: 13295

Answers (2)

Milosz Skurowski
Milosz Skurowski

Reputation: 1

To declare the type hint of 'self' for Python 3.7, you need to import:

  from future__ import annotations

at the beginning of the file. That's all you need to do. From now you can use same class type hint:

def isSamePoint (self, p: Point) -> bool:

instead of class name as a string:

def isSamePoint (self, p: 'Point') -> bool:

Upvotes: 0

Tom Wojcik
Tom Wojcik

Reputation: 6189

TypeError: 'type' object is not subscriptable

Python 3.9 allows for list[str]. Earlier you had to import List from typing and do -> List[str].

NameError: name 'Point' is not defined

If you want to declare the type of "self" you can either put that in a string def isSamePoint(self, p: "Point") -> bool: or create an interface.

>>> class A: pass
>>> class B(A): pass
>>> b = B()
>>> isinstance(b, A)
True

so def isSamePoint(self, p: A) would do the trick.

Also, if you want to check if isSamePoint you might want to consider your own __eq__.

Upvotes: 12

Related Questions