P1sec / pycrate

A Python library to ease the development of encoders and decoders for various protocols and file formats; contains ASN.1 and CSN.1 compilers.
GNU Lesser General Public License v2.1
380 stars 130 forks source link

Code is unreachable issue using Pylance #217

Open turabek-cc opened 1 year ago

turabek-cc commented 1 year ago

I am using Pylance and while the Pycrate code works, some parts after encoding/decoding are grayed out as unreachable. The easiest solution is replacing 'ASN1NotSuppErr' with 'NotImplementedError' in 'pycrate_asn1rt/asnobj.py'. Other options are given at https://github.com/microsoft/pylance-release/issues/2092#issuecomment-1022571313 It would be a nice improvement for those who use static type analyzers.

Pycrate version: 0.5.5 Pylance version: v2022.11.30

Example to reproduce the issue.

from pycrate_asn1dir.ITS_IEEE1609_2 import Ieee1609Dot2BaseTypes

signature = Ieee1609Dot2BaseTypes.Signature

signature.from_coer(
    bytes.fromhex(
        "808211111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
    )
)

print(signature.get_val()) # shown unreachable, but reachable 
p1-bmu commented 1 year ago

Thanks for the report. I don't know Pylance, but apparently, they have some strong assumptions on the Python code it's working on (at least stronger than the Python2 or 3 runtine, and stronger than pypy). I am basically not in favour of doing code modification just to comply with some or other frameworks. Moreover, I do not use vscode, neither this Pylance extension. Eventually, if you propose a short / tiny patch to pycrate for your case to work, I may integrate it in master (and replacing a custom pycrate exception by a defaut Python one is not something nice, as any code that catches on custom pycrate exception will fail after this modification).

Regards Benoit

turabek-cc commented 1 year ago

Thanks for the quick reply. It seems other solutions, adding a return type or using abstract classes, cannot be applied because of Python2 support. Type hints require Python 3.5+, whereas abstract class signatures are different for Python 2 and Python 3. Moreover, I can see many instantiations of ASN1Obj, which is impossible for abstract classes. Probably, we will need to wait for Pycrate to abandon Python 2 support, then add type hints directly in the source code. Or separate stub files can be added which are ignored by Python2 as far as I know. For my local development, I created a stub file 'pycrate_asn1rt/asnobj.pyi' with the following contents:

def _from_asn1(self, txt) -> None: ...

def _to_asn1(self) -> str: ...

def _from_oer(self, char) -> None: ...

def _to_oer(self) -> bytes: ...