Typing stubs for pyasn1

0.6.0.20260408 · active · verified Fri Apr 10

This package provides typing stubs for the `pyasn1` library, enabling static type checkers like MyPy and PyRight to validate code that uses `pyasn1`. It is part of the typeshed project, a collection of high-quality type annotations, and aims to provide accurate annotations for `pyasn1==0.6.*`. Typeshed releases stub packages automatically, often up to once a day, reflecting changes and improvements to the types.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define an ASN.1 `SEQUENCE` type, create an instance, populate it with data, and then encode and decode it using `pyasn1`. The `types-pyasn1` package ensures that static type checkers can validate the usage of `pyasn1` types and methods, catching potential type mismatches or incorrect attribute access at design time.

from pyasn1.type import univ, namedtype
from pyasn1.codec.der import encoder, decoder

# Define an ASN.1 structure (Record) using pyasn1 types
class Record(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('id', univ.Integer()),
        namedtype.OptionalNamedType('name', univ.OctetString())
    )

# Create an instance and set values
record = Record()
record['id'] = 123  # Type checkers will ensure 'id' is an Integer
record['name'] = univ.OctetString('Example Name') # Type checkers will ensure 'name' is an OctetString

# Encode to DER
encoded_data = encoder.encode(record)
print(f"Encoded: {encoded_data.hex()}")

# Decode from DER (asn1Spec provides the expected type for decoding)
decoded_record, rest = decoder.decode(encoded_data, asn1Spec=Record())
print(f"Decoded ID: {decoded_record['id']}")
print(f"Decoded Name: {decoded_record['name']}")

# Example of type checking: if 'id' was assigned a string, a type checker would flag it.
# For instance, 'record['id'] = "not_an_int"' would cause a type error.

view raw JSON →