Summary
Annotating anything with a PEP 604 union (X | None, X | Y) fails to load, with an error that doesn't obviously point to "pyscript doesn't support this syntax":
TypeError: unsupported operand type(s) for |: 'EvalLocalVar' and 'NoneType'
Environment
- pyscript 2.1.0 (HACS)
allow_all_imports: true, hass_is_global: true, legacy_decorators: false
Reproduction
In a pyscript app file:
from dataclasses import dataclass
@dataclass
class Foo:
bar: int | None = None
The error above shows up in the logs on pyscript.reload.
The same failure happens on a plain module-level annotation (x: SomeLocalClass | None = None), not just inside a dataclass. Swapping to typing.Optional[X] (or typing.Union[X, Y]) loads fine. It is confusing, though, because X | None is the current Python idiom, and what tools like ruff --fix actively rewrite Optional[X] into by default, so it's easy to fall into this one and get the confusing error message.
Fix
Primarily, I think it would be worth adding this to the Language Limitations section to help others not fall into this oops, ideally with the error text as a search anchor. I'd be happy to submit a quick docs PR covering this if you'd like.
In the longer term, support for | in annotations would be nice - it is the current Python idiom, after all - but that'd involve interpreter work not just a quick fix.
Happy to help with repros or patch testing if that'd be useful to you.
Summary
Annotating anything with a PEP 604 union (
X | None,X | Y) fails to load, with an error that doesn't obviously point to "pyscript doesn't support this syntax":Environment
allow_all_imports: true,hass_is_global: true,legacy_decorators: falseReproduction
In a pyscript app file:
The error above shows up in the logs on
pyscript.reload.The same failure happens on a plain module-level annotation (x: SomeLocalClass | None = None), not just inside a dataclass. Swapping to typing.Optional[X] (or typing.Union[X, Y]) loads fine. It is confusing, though, because
X | Noneis the current Python idiom, and what tools likeruff --fixactively rewriteOptional[X]into by default, so it's easy to fall into this one and get the confusing error message.Fix
Primarily, I think it would be worth adding this to the Language Limitations section to help others not fall into this oops, ideally with the error text as a search anchor. I'd be happy to submit a quick docs PR covering this if you'd like.
In the longer term, support for
|in annotations would be nice - it is the current Python idiom, after all - but that'd involve interpreter work not just a quick fix.Happy to help with repros or patch testing if that'd be useful to you.