• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: New union shorthand giving “unsupported operand type(s) for |: ‘str’ and ‘type'”

Resolved: New union shorthand giving “unsupported operand type(s) for |: ‘str’ and ‘type'”

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

Before 3.10, I was using Union to create union parameter annotations:
Now, when I use the new union shorthand syntax:
I get the error:

TypeError: unsupported operand type(s) for |: ‘str’ and ‘type’


Is this not supported?

Answer:

The fact that it’s being used as a type hint doesn’t really matter; fundamentally the expression "Vector" | float is a type error because strings don’t support the | operator, they don’t implement __or__. To get this passing, you have three options:
  1. Defer evaluation (see PEP 563):

    from __future__ import annotations
    
    class Vector:
        def __mul__(self, other: Vector | float): ...
    
  2. Make the whole type a string (effectively the same as deferring evaluation):

    class Vector:
        def __mul__(self, other: "Vector | float"): ...
    
  3. Keep using the Union:

    from typing import Union
    
    class Vector:
        def __mul__(self, other: Union["Vector", float]): ...
    

You can see further discussion, without a resolution as yet, on this bug.

If you have better answer, please add a comment about this, thank you!

python python-3.10 type-hinting
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Java Virtual Machines deleted

27/03/2023

Resolved: PyCharm cannot see my newly compiled .pyc see on import

27/03/2023

Resolved: I am facing ERR_HTTP2_PROTOCOL_ERROR on my website

27/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.