Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Confusing code snippet in type.Literal docs #120561

Closed
nhstanley opened this issue Jun 15, 2024 · 1 comment
Closed

Confusing code snippet in type.Literal docs #120561

nhstanley opened this issue Jun 15, 2024 · 1 comment
Labels
docs Documentation in the Doc dir topic-typing

Comments

@nhstanley
Copy link

Documentation

There is a confusing use of type in a code snippet for typing.Literal). Link to section. Here is the code snippet in question, reproduced here:

def validate_simple(data: Any) -> Literal[True]:  # always returns True
    ...

type Mode = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: Mode) -> str:
    ...

open_helper('/some/path', 'r')      # Passes type check
open_helper('/other/path', 'typo')  # Error in type checker

Line 4 is the problematic one. At first when I saw this, I thought that maybe the type function can also serve as a keyword/statement, like the old print statement in python2. However, it throws a SyntaxError, as expected if type is only a function.

Re-writing it slightly, this code is actually runnable and checkable with mypy:

from typing import Literal, Any
def validate_simple(data: Any) -> Literal[True]:  # always returns True
    ...

Mode = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: Mode) -> str:
    ...

open_helper('/some/path', 'r')      # Passes type check
open_helper('/other/path', 'typo')  # Error in type checker

While I realize not all code snippets are meant to be executable, I think this one is confusing. If others agree, I'd be happy to write a PR with the updated snippet.

@nhstanley nhstanley added the docs Documentation in the Doc dir label Jun 15, 2024
@JelleZijlstra
Copy link
Member

The type keyword is new syntax added in Python 3.12 (PEP-695). Mypy does not support it yet, but it will soon.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Jun 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Documentation in the Doc dir topic-typing
Projects
None yet
Development

No branches or pull requests

2 participants