I use coc-pyright as python code completer in debian. When I work on a django file, I get errors like this error in neovim env. But django runs codes without any problem. I have installed django with apt and not with pip and also I am not in a venv.

  • ComradeMoustache@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    1 year ago

    The “error” says that it is expecting byte rather than a str. What you’re seeing here isn’t really an error, it’s the pyright typechecker telling you that the function definition and your input are misaligned. It could be that the function signature is incorrect and it actually can take a string, or it could be that this string works as the functions down the line just happen to work with that string. Another string might not. You can fix this by encoding the string with b"my string" or "my string".encode("utf-8"). I may have got the syntax wrong as i’m not able to test it at the moment.

    Remember that type hints are just hints, so python will run the code regardless of whether the input matches the signature. If you’re coming from a compiled language this can seem a bit strange as you might expect the types to be enforced but python is duck typed so it will try to run the code anyway. If a function said it only needed an int (def my_func(input: int) -> int:), and you passed in a string, you may not get an error if said function only runs code on the string input that overlaps with the int functionality (I.e. both ints and strings can be muliplied, 2*2 becomes 4 but "4"*2 becomes “4”), but you might see some unexpected behaviour. So you may not notice the error until the code hits a branch that doesn’t have overlap. If you’d passed a float in this case that was 2.0 you would get 4.0 out which could work fine as 4 and 4.0 would behave the same in your code (assuming there’s no floating point imprecisions) until you try to use it to index into a list, my_list[4.0], so the type signature is correct but the value you used just happened to work in that context.

    Python strings are Unicode encoded, as opposed to byte encoded (none of the characters you’ve used use more than one byte, so maybe this would error, or cause unexpected behaviour, if you tried a character that uses more than one byte 🤷, but i’m really just guessing at this point) https://stackoverflow.com/questions/10060411/byte-string-vs-unicode-string-python

    • Reza Hosseinzadeh@programming.devOP
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      Thank you for your complete explanation! Now I have a question. I know that this note that coc-pyright shows does not hurt code’s running. But the note hurts me when I am coding. Do you know how to remove pyright’s type hint?