Typing stubs for pyasn1
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
- gotcha The `types-pyasn1` package provides type annotations for a specific version range of `pyasn1` (currently `0.6.*`). Using it with a significantly different version of the runtime `pyasn1` library may lead to inaccurate type checking results or false positives/negatives.
- gotcha This is a 'stub-only' package, meaning it contains only type hint files (`.pyi`) and no runtime Python code. You must install the actual `pyasn1` library separately for your code to execute. `types-pyasn1` is only for static analysis.
- gotcha Typeshed stub package versions follow a `X.Y.Z.YYYYMMDD` format. The `X.Y.Z` part indicates the `pyasn1` version the stubs target, while `YYYYMMDD` is the stub release date. Pinning only `X.Y.Z` (e.g., `types-pyasn1==0.6.0`) might still result in updates from newer daily stub releases if not fully pinned (e.g., `types-pyasn1==0.6.0.20260408`).
- breaking While typeshed aims for stability, changes within the stub files themselves can introduce stricter type checks or corrections that may cause existing, untyped, or loosely typed code using `pyasn1` to suddenly fail type checking, even if the runtime `pyasn1` version has not changed.
Install
-
pip install types-pyasn1
Imports
- Integer
from pyasn1.type import univ
- Sequence
from pyasn1.type import univ
- NamedType
from pyasn1.type import namedtype
Quickstart
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.