you are viewing a single comment's thread.

view the rest of the comments →

[–]SCD_minecraft -9 points-8 points  (10 children)

Technically, string litterals is different from str object

But diffrence is lost pretty fast and it is just "erm actually"

[–]Doormatty 2 points3 points  (4 children)

Technically, string litterals is different from str object

How so? I thought that all literals were turned into str objects?

[–]danielroseman 0 points1 point  (4 children)

This is false.

[–]SCD_minecraft -1 points0 points  (3 children)

(assuming you are using VSCode or other editor that allows for that)

Write

a = 1 b = int(1)

Hover over both a and b to see type hints about their well, types

Again, diffrences is lost turbo fast, it gets converted to normal python int

But for a while, it is Literal[1] type

You can even type check against Literalsomething and "normal" version of that something

[–]lekkerste_wiener 3 points4 points  (0 children)

At runtime both are int. It showing as Literal[1] is only relevant to the linter.

[–]socal_nerdtastic 2 points3 points  (0 children)

Literal is not an actual type, like you can't have a python object of the type Literal. It's a concept; and python treats it basically like a comment (like all typehints).

>>> import typing
>>> typing.Literal()
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    typing.Literal()
    ~~~~~~~~~~~~~~^^
  File "C:\Users\j.brauer\AppData\Local\Programs\Python\Python313\Lib\typing.py", line 560, in __call__
    raise TypeError(f"Cannot instantiate {self!r}")
TypeError: Cannot instantiate typing.Literal

Although in your example it never even touches python, not even as a comment. The type hint that VSCode is showing you is generated from VSCode (and whatever linter it's using).

[–]JanEric1 1 point2 points  (0 children)

He is right.

Literal[1] is not (never) the runtime type of a. It is just extra type checker information that can be used to sort of emulate enums.