rspec/rules/S6546/python/rule.adoc

54 lines
1.3 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
Python 3.10 introduced a specific syntax using the "or" operator (`X | Y`) to represent a union of types.
This syntax has the same functionality as `typing.Union`, but it is more concise and easier to read.
Using `typing.Union` is more verbose and less convenient. It can also create inconsistencies when different parts of the codebase use different syntaxes for the same type.
== How to fix it
Replace usages of `typing.Union` with the union type syntax.
=== Code examples
==== Noncompliant code example
[source,python]
----
from typing import Union
def foo(arg: Union[int, str]) -> Union[int, str]:
if isinstance(arg, int):
return arg + 1
else:
return arg.upper()
----
==== Compliant solution
[source,python]
----
def foo(arg: int | str) -> int | str:
if isinstance(arg, int):
return arg + 1
else:
return arg.upper()
----
== Resources
=== Documentation
- https://peps.python.org/pep-0604/[PEP 604 - Allow writing union types as X | Y]
- https://docs.python.org/3/library/stdtypes.html#types-union[Python documentation on union type expressions]
ifdef::env-github,rspecator-view[]
== Implementation Specification
(visible only on this page)
=== Message
Use a union type expression for this type hint.
endif::env-github,rspecator-view[]