Skip to content

Docs gap (and possible fix candidate): X | None union annotations fail to load — TypeError: unsupported operand type(s) for |: 'EvalLocalVar' and 'NoneType' #875

Description

@cerebrate

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions