I'm trying to create several int constants for my module, initialized from the hex values. Pylance keeps complaining about the type conversion errors, but I don't see why and how.
Consider the following code:
from micropython import const
_AHT21_I2CADDR_DEFAULT: int = const(0x38) #Default I2C address
_AHT21_CMD_CALIBRATE: bytes = const(0xE1) # Calibration command
For the second line, the error message it shows is:
Expression of type "int | bytes | str | Tuple[Unknown, ...]" cannot be assigned to declared type "int" Type "int | bytes | str | Tuple[Unknown, ...]" cannot be assigned to type "int" "bytes" is incompatible with "int"
For the third line, the message is almost identical except for "bytes" and "int" swapped:
Expression of type "int | bytes | str | Tuple[Unknown, ...]" cannot be assigned to declared type "bytes" Type "int | bytes | str | Tuple[Unknown, ...]" cannot be assigned to type "bytes" "int" is incompatible with "bytes"
That's right, the errors are the complete opposite of one another.
The code, however, runs fine on the board (if I change the third line from bytes to int, of course - int is the correct type here), which makes me think there is no actual error.
How do I make Pylance not raise this error?
Edited to add: It looks like pylance doesn't like when you use a function that can return different types with type hints, it tries to enforce ALL types instead of ANY type and fails.
For example, I've defined a function:
def read(self, count:int = 1) -> Union[int, bytes]:
that reads a number of bytes from the device. It returns either an integer if only a single byte is read, or a bytes string otherwise.
When trying to use it like this:
self._trim: bytes = self._i2c.read(0x18)
pylance raises an error that "int" is incompatible with "bytes".
So the question is now: is it possible to make Pylance work with multiple-valued type hints or am I better to just disable reportGeneralTypeIssues check in the project, as I'm using it all throughout?
# type: ignoreto each line.