Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list type declaration

Tags:

python

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.

like image 653
Alisa Kunapinun Avatar asked Mar 01 '23 23:03

Alisa Kunapinun


1 Answers

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__.

like image 137
Tom Wojcik Avatar answered Mar 04 '23 13:03

Tom Wojcik