0

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?

2
  • My guess is that pylance doesn't know anything about Micropython-specific syntax. Probably the easiest solution is to add a # type: ignore to each line. Commented Jul 14, 2023 at 3:47
  • See my edit for additional details. It doesn't seem to be a Micropython-specific syntax. Commented Jul 14, 2023 at 5:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.