N
N
Nikolai2020-06-07 14:03:09
Python
Nikolai, 2020-06-07 14:03:09

What is Optional[] used for?

It is not clear why and how Optional[] is used.
In the example below, I'm setting a variable of type Optional[Point]. I expected that when assigning a value to a variable of a different type, a run-time error will fly out, but no. Quietly assigned to both 5 and "hello". What's the point of using Optional then? Or am I doing something wrong?

from typing import Optional

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

    def __str__(self):
        return str(self.x)


a : Optional[Point]
b : Optional[Point]
c : Optional[Point]


a = None      # 
b = 5             #здесь должна быть ошибка ??
c = Point(22)
a = "hello"     #здесь должна быть ошибка ??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-06-07
@vnkama

Type annotations are indifferent to the interpreter. We can say that these are just strict comments that linters can react to, and that's it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question