Skip to content

Conversation

jhoward-lm
Copy link
Contributor

This PR updates union type annotations to use the PEP-604 pipe operator, changing type hints like this:

Optional[Union[str, Dict[str, str]]]

to this:

str | dict[str, str] | None

The changes were auto-generated by running pyupgrade --py38-plus src/packageurl/__init__.py. It switches to using built-in types dict and tuple rather than typing.Dict and typing.Tuple.

Miscellaneous

  • applied refactorings suggested by sourcery
    • assign-if-exp: replace if statements, e.g.:
       if isinstance(s, str):
           s_bytes = s.encode("utf-8")
       else:
           s_bytes = s
      with if expressions:
      s_bytes = s.encode("utf-8") if isinstance(s, str) else s
    • avoid-builtin-shadow: don't assign to builtin variable type (renames local variable type to type_ in PackageURL.from_string())
  • applied fixes suggested by ruff
    • RUF010: Use explicit conversion flag (change instances of f"{repr(value)}" to f"{value!r}")

@jhoward-lm
Copy link
Contributor Author

@tdruez @gruebel Here's the follow-on PR for what we discussed in this comment

@tdruez tdruez merged commit 6f38e3e into package-url:main Oct 31, 2024
19 checks passed
@jhoward-lm jhoward-lm deleted the pep-604-union-types branch October 31, 2024 06:12
@mjherzog mjherzog added this to the v0.16.1 milestone May 22, 2025
@jkowalleck
Copy link
Member

jkowalleck commented Jun 5, 2025

the pipe syntax is not available before python v8.10
the very library supports python 3.8

does this change cause no issues?

I mean, the lint/mypy might not properly detect - they run in py3.9 --

python-version: "3.9"

I would at least expect that build-and-test CI/CT detects issues running on py3.8.
tested:

$ docker run --rm -it --entrypoint python python:3.8.0 -c "
  from typing import Union
  AnyStr = Union[str, bytes]
  def normalize_type(type: AnyStr | None, encode: bool | None = True) -> str | None:
    pass
  "
Traceback (most recent call last):
  File "<string>", line 4, in <module>
TypeError: unsupported operand type(s) for |: '_GenericAlias' and 'NoneType'

@jhoward-lm
Copy link
Contributor Author

@jkowalleck try also adding from __future__ import annotations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants