Skip to content

TypeError for threading.Lock | None #114315

Closed
@Mark90

Description

@Mark90

Bug report

Bug description:

I tried to search for a related ticket by various queries but did not find any, hopefully I haven't overlooked it.

While rewriting a codebase from Optional[foo] to the newer foo | None style, I encountered that threading.Lock does not allow the latter.

Example on MacOS 3.12.1:

>>> from typing import Optional
>>> from threading import Lock
>>> Optional[Lock]
typing.Optional[<built-in function allocate_lock>]
>>> Lock | None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'builtin_function_or_method' and 'NoneType'

Given that the documentation states the following, the error makes sense:

Note that Lock is actually a factory function which returns an instance of the most efficient version of the concrete Lock class that is supported by the platform.

I actually didn't know it was a factory function. I would not intentionally create a <function> | None type. But since the documentation describes threading.Lock as a class, one would expect to be able to use it as any other type.

CPython versions tested on:

3.11, 3.12, 3.13.0a3

Operating systems tested on:

Linux, macOS

Linked PRs

Metadata

Metadata

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions