Skip to content

[ENH] Implement "typing.Optional[]" and give it Python semantics ("not None" vs. "or None") #3883

@scoder

Description

@scoder

In Cython, def func(list arg) allows arg to be None. In Python's PEP-484 typing universe, def func(arg: list) excludes None and passing None requires the spelling def func(arg: Optional[list]).

Given that Optional[…] exists, we could change the type analysis of PEP-484 argument annotations to exclude None by default (i.e. interpret them as if not None was given), since this it is a common source of mistakes (see #2696). The use of Optional[] would then be interpreted as or None.

This would probably not apply to variable annotations. While PEP-526 doesn't seem to mention the topic anywhere explicitly, it seems hard to prevent variables from being set to None, and it has a runtime impact to prevent that case. Also, it does not seem very useful to actively prevent users from setting variables to None.

Also note that there is the issue of subtypes, which Python typing allows but Cython typing rejects. This difference would probably remain.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions