Module hat.asn1

Abstract Syntax Notation One

Value mapping:

+-----------------------+------------------+
| ASN.1 type            | Python type      |
+=======================+==================+
| Boolean               | bool             |
+-----------------------+------------------+
| Integer               | int              |
+-----------------------+------------------+
| BitString             | List[bool]       |
+-----------------------+------------------+
| OctetString           | bytes            |
+-----------------------+------------------+
| Null                  | <code>None</code>         |
+-----------------------+------------------+
| ObjectIdentifier      | List[int]        |
+-----------------------+------------------+
| String                | str              |
+-----------------------+------------------+
| External              | External         |
+-----------------------+------------------+
| Real                  | float            |
+-----------------------+------------------+
| Enumerated            | int              |
+-----------------------+------------------+
| EmbeddedPDV           | EmbeddedPDV      |
+-----------------------+------------------+
| Choice                | Tuple[str,Value] |
+-----------------------+------------------+
| Set                   | Dict[str,Value]  |
+-----------------------+------------------+
| SetOf                 | Iterable[Value]  |
+-----------------------+------------------+
| Sequence              | Dict[str,Value]  |
+-----------------------+------------------+
| SequenceOf            | List[Value]      |
+-----------------------+------------------+
| ABSTRACT-SYNTAX.&Type | Entity           |
+-----------------------+------------------+

For Choice, Set and Sequence, <code><a title="hat.asn1.str" href="#hat.asn1.str">str</a></code> represents field name.
Expand source code
"""Abstract Syntax Notation One

Value mapping:

    +-----------------------+------------------+
    | ASN.1 type            | Python type      |
    +=======================+==================+
    | Boolean               | bool             |
    +-----------------------+------------------+
    | Integer               | int              |
    +-----------------------+------------------+
    | BitString             | List[bool]       |
    +-----------------------+------------------+
    | OctetString           | bytes            |
    +-----------------------+------------------+
    | Null                  | ``None``         |
    +-----------------------+------------------+
    | ObjectIdentifier      | List[int]        |
    +-----------------------+------------------+
    | String                | str              |
    +-----------------------+------------------+
    | External              | External         |
    +-----------------------+------------------+
    | Real                  | float            |
    +-----------------------+------------------+
    | Enumerated            | int              |
    +-----------------------+------------------+
    | EmbeddedPDV           | EmbeddedPDV      |
    +-----------------------+------------------+
    | Choice                | Tuple[str,Value] |
    +-----------------------+------------------+
    | Set                   | Dict[str,Value]  |
    +-----------------------+------------------+
    | SetOf                 | Iterable[Value]  |
    +-----------------------+------------------+
    | Sequence              | Dict[str,Value]  |
    +-----------------------+------------------+
    | SequenceOf            | List[Value]      |
    +-----------------------+------------------+
    | ABSTRACT-SYNTAX.&Type | Entity           |
    +-----------------------+------------------+

    For Choice, Set and Sequence, `str` represents field name.

"""

import enum
import pathlib
import typing

from hat import json
from hat.asn1 import ber
from hat.asn1 import common
from hat.asn1 import doc
from hat.asn1.common import (Data,
                             Value,
                             Boolean,
                             Integer,
                             BitString,
                             OctetString,
                             Null,
                             ObjectIdentifier,
                             String,
                             External,
                             Real,
                             Enumerated,
                             EmbeddedPDV,
                             Choice,
                             Set,
                             SetOf,
                             Sequence,
                             SequenceOf,
                             Entity,
                             is_oid_eq)


__all__ = ['Data',
           'Value',
           'Boolean',
           'Integer',
           'BitString',
           'OctetString',
           'Null',
           'ObjectIdentifier',
           'String',
           'External',
           'Real',
           'Enumerated',
           'EmbeddedPDV',
           'Choice',
           'Set',
           'SetOf',
           'Sequence',
           'SequenceOf',
           'Entity',
           'is_oid_eq',
           'Encoding',
           'Encoder',
           'Repository']


Encoding = enum.Enum('Encoding', ['BER'])


class Repository:
    """ASN.1 type definition repository.

    Repository can be initialized with multiple arguments, which can be
    instances of ``pathlib.PurePath``, ``str`` or ``Repository``.

    If an argument is of type ``pathlib.PurePath``, and path points to file
    with a suffix '.asn', ASN.1 type definitions are decoded from the file.
    Otherwise, it is assumed that path points to a directory,
    which is recursively searched for ASN.1 definitions. All decoded types
    are added to the repository. Previously added type definitions with the
    same references are replaced.

    If an argument is of type ``str``, it represents ASN.1 type definitions.
    All decoded types are added to the repository. Previously added type
    definitions with the same references are replaced.

    If an argument is of type ``Repository``, its data definitions are added to
    the new repository. Previously added type definitions with the
    same references are replaced.

    """

    def __init__(self, *args: typing.Union[pathlib.PurePath,
                                           str,
                                           'Repository']):
        self._refs = {}
        for arg in args:
            if isinstance(arg, pathlib.PurePath):
                self._load_path(arg)
            elif isinstance(arg, str):
                self._parse_asn1_def(arg)
            elif isinstance(arg, Repository):
                self._refs.update(arg._refs)
            else:
                raise ValueError('invalid argument')

    @staticmethod
    def from_json(data: typing.Union[pathlib.PurePath, json.Data]
                  ) -> 'Repository':
        """Create repository from JSON data representation"""
        if isinstance(data, pathlib.PurePath):
            data = json.decode_file(data)
        repo = Repository()
        repo._refs = {common.type_from_json(k): common.type_from_json(v)
                      for k, v in data}
        return repo

    def to_json(self) -> json.Data:
        """Represent repository as JSON data"""
        return [[common.type_to_json(k), common.type_to_json(v)]
                for k, v in self._refs.items()]

    def generate_html_doc(self) -> str:
        """Generate HTML documentation"""
        return doc.generate_html(self._refs)

    def _load_path(self, path):
        paths = [path] if path.suffix == '.asn' else path.rglob('*.asn')
        for path in paths:
            with open(path, 'r', encoding='utf-8') as f:
                asn1_def = f.read()
            self._parse_asn1_def(asn1_def)

    def _parse_asn1_def(self, asn1_def):
        from hat.asn1 import parser
        refs = parser.parse(asn1_def)
        self._refs.update(refs)


class Encoder:
    """ASN1 Encoder"""

    def __init__(self,
                 encoding: Encoding,
                 repository: Repository):
        self._encoding = encoding
        self._repository = repository

    @property
    def syntax_name(self) -> ObjectIdentifier:
        """Encoder syntax name"""
        if self._encoding == Encoding.BER:
            return ber.syntax_name
        raise ValueError('invalid encoding')

    def encode(self,
               module: str,
               name: str,
               value: Value
               ) -> Data:
        """Encode value to data"""
        entity = self.encode_value(module, name, value)
        data = self.encode_entity(entity)
        return data

    def decode(self,
               module: str,
               name: str,
               data: Data
               ) -> typing.Tuple[Value, Data]:
        """Decode value from data

        Returns value and remaining data.

        """
        entity, rest = self.decode_entity(data)
        value = self.decode_value(module, name, entity)
        return value, rest

    def encode_value(self,
                     module: str,
                     name: str,
                     value: Value
                     ) -> Entity:
        """Encode value to entity"""
        if self._encoding == Encoding.BER:
            return ber.encode_value(self._repository._refs,
                                    common.TypeRef(module, name),
                                    value)
        raise ValueError('invalid encoding')

    def decode_value(self,
                     module: str,
                     name: str,
                     entity: Entity
                     ) -> Value:
        """Decode value from entity"""
        if self._encoding == Encoding.BER:
            return ber.decode_value(self._repository._refs,
                                    common.TypeRef(module, name),
                                    entity)
        raise ValueError('invalid encoding')

    def encode_entity(self,
                      entity: Entity
                      ) -> Data:
        """Encode entity to data"""
        if self._encoding == Encoding.BER:
            return ber.encode_entity(entity)
        raise ValueError('invalid encoding')

    def decode_entity(self,
                      data: Data
                      ) -> typing.Tuple[Entity, Data]:
        """Decode entity from data

        Returns entity and remaining data.

        """
        if self._encoding == Encoding.BER:
            return ber.decode_entity(data)
        raise ValueError('invalid encoding')

Sub-modules

hat.asn1.ber
hat.asn1.common
hat.asn1.doc
hat.asn1.parser

Functions

def is_oid_eq(x: typing.List[typing.Union[int, typing.Tuple[strint]]], y: typing.List[typing.Union[int, typing.Tuple[strint]]]) ‑> bool

Check if two ASN.1 object identifiers are equal

Expand source code
def is_oid_eq(x: ObjectIdentifier,
              y: ObjectIdentifier
              ) -> bool:
    """Check if two ASN.1 object identifiers are equal"""
    if len(x) != len(y):
        return False
    for i, j in zip(x, y):
        i_id = i if isinstance(i, int) else i[1]
        j_id = j if isinstance(j, int) else j[1]
        if i_id != j_id:
            return False
    return True

Classes

class EmbeddedPDV (abstract: typing.Union[int, typing.List[typing.Union[int, typing.Tuple[strint]]], NoneType], transfer: typing.Union[typing.List[typing.Union[int, typing.Tuple[strint]]], NoneType], data: typing.Union[bytes, bytearray, memoryview])

EmbeddedPDV(abstract, transfer, data)

Expand source code
class EmbeddedPDV(typing.NamedTuple):
    abstract: typing.Optional[typing.Union[int, ObjectIdentifier]]
    transfer: typing.Optional[ObjectIdentifier]
    data: Data

Ancestors

  • builtins.tuple

Instance variables

var abstract : typing.Union[int, typing.List[typing.Union[int, typing.Tuple[strint]]], NoneType]

Alias for field number 0

var data : typing.Union[bytes, bytearray, memoryview]

Alias for field number 2

var transfer : typing.Union[typing.List[typing.Union[int, typing.Tuple[strint]]], NoneType]

Alias for field number 1

class Encoder (encoding: Encoding, repository: Repository)

ASN1 Encoder

Expand source code
class Encoder:
    """ASN1 Encoder"""

    def __init__(self,
                 encoding: Encoding,
                 repository: Repository):
        self._encoding = encoding
        self._repository = repository

    @property
    def syntax_name(self) -> ObjectIdentifier:
        """Encoder syntax name"""
        if self._encoding == Encoding.BER:
            return ber.syntax_name
        raise ValueError('invalid encoding')

    def encode(self,
               module: str,
               name: str,
               value: Value
               ) -> Data:
        """Encode value to data"""
        entity = self.encode_value(module, name, value)
        data = self.encode_entity(entity)
        return data

    def decode(self,
               module: str,
               name: str,
               data: Data
               ) -> typing.Tuple[Value, Data]:
        """Decode value from data

        Returns value and remaining data.

        """
        entity, rest = self.decode_entity(data)
        value = self.decode_value(module, name, entity)
        return value, rest

    def encode_value(self,
                     module: str,
                     name: str,
                     value: Value
                     ) -> Entity:
        """Encode value to entity"""
        if self._encoding == Encoding.BER:
            return ber.encode_value(self._repository._refs,
                                    common.TypeRef(module, name),
                                    value)
        raise ValueError('invalid encoding')

    def decode_value(self,
                     module: str,
                     name: str,
                     entity: Entity
                     ) -> Value:
        """Decode value from entity"""
        if self._encoding == Encoding.BER:
            return ber.decode_value(self._repository._refs,
                                    common.TypeRef(module, name),
                                    entity)
        raise ValueError('invalid encoding')

    def encode_entity(self,
                      entity: Entity
                      ) -> Data:
        """Encode entity to data"""
        if self._encoding == Encoding.BER:
            return ber.encode_entity(entity)
        raise ValueError('invalid encoding')

    def decode_entity(self,
                      data: Data
                      ) -> typing.Tuple[Entity, Data]:
        """Decode entity from data

        Returns entity and remaining data.

        """
        if self._encoding == Encoding.BER:
            return ber.decode_entity(data)
        raise ValueError('invalid encoding')

Instance variables

var syntax_name : typing.List[typing.Union[int, typing.Tuple[strint]]]

Encoder syntax name

Expand source code
@property
def syntax_name(self) -> ObjectIdentifier:
    """Encoder syntax name"""
    if self._encoding == Encoding.BER:
        return ber.syntax_name
    raise ValueError('invalid encoding')

Methods

def decode(self, module: str, name: str, data: typing.Union[bytes, bytearray, memoryview]) ‑> typing.Tuple[typing.Union[boolint, typing.List[bool], bytes, NoneType, typing.List[typing.Union[int, typing.Tuple[strint]]], strExternalfloatintEmbeddedPDV, typing.Tuple[str, typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], typing.Dict[str, typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], typing.Iterable[typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], typing.Dict[str, typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], typing.List[typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], Entity], typing.Union[bytes, bytearray, memoryview]]

Decode value from data

Returns value and remaining data.

Expand source code
def decode(self,
           module: str,
           name: str,
           data: Data
           ) -> typing.Tuple[Value, Data]:
    """Decode value from data

    Returns value and remaining data.

    """
    entity, rest = self.decode_entity(data)
    value = self.decode_value(module, name, entity)
    return value, rest
def decode_entity(self, data: typing.Union[bytes, bytearray, memoryview]) ‑> typing.Tuple[Entity, typing.Union[bytes, bytearray, memoryview]]

Decode entity from data

Returns entity and remaining data.

Expand source code
def decode_entity(self,
                  data: Data
                  ) -> typing.Tuple[Entity, Data]:
    """Decode entity from data

    Returns entity and remaining data.

    """
    if self._encoding == Encoding.BER:
        return ber.decode_entity(data)
    raise ValueError('invalid encoding')
def decode_value(self, module: str, name: str, entity: Entity) ‑> typing.Union[boolint, typing.List[bool], bytes, NoneType, typing.List[typing.Union[int, typing.Tuple[strint]]], strExternalfloatintEmbeddedPDV, typing.Tuple[str, typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], typing.Dict[str, typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], typing.Iterable[typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], typing.Dict[str, typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], typing.List[typing.Union[boolint, BitString, bytes, Null, ObjectIdentifier, strExternalfloatintEmbeddedPDV, Choice, Set, SetOf, Sequence, SequenceOf, Entity]], Entity]

Decode value from entity

Expand source code
def decode_value(self,
                 module: str,
                 name: str,
                 entity: Entity
                 ) -> Value:
    """Decode value from entity"""
    if self._encoding == Encoding.BER:
        return ber.decode_value(self._repository._refs,
                                common.TypeRef(module, name),
                                entity)
    raise ValueError('invalid encoding')
def encode(self, module: str, name: str, value: typing.Union[ForwardRef('bool'), ForwardRef('int'), ForwardRef('BitString'), ForwardRef('bytes'), ForwardRef('Null'), ForwardRef('ObjectIdentifier'), ForwardRef('str'), ForwardRef('External'), ForwardRef('float'), ForwardRef('int'), ForwardRef('EmbeddedPDV'), ForwardRef('Choice'), ForwardRef('Set'), ForwardRef('SetOf'), ForwardRef('Sequence'), ForwardRef('SequenceOf'), ForwardRef('Entity')]) ‑> typing.Union[bytes, bytearray, memoryview]

Encode value to data

Expand source code
def encode(self,
           module: str,
           name: str,
           value: Value
           ) -> Data:
    """Encode value to data"""
    entity = self.encode_value(module, name, value)
    data = self.encode_entity(entity)
    return data
def encode_entity(self, entity: Entity) ‑> typing.Union[bytes, bytearray, memoryview]

Encode entity to data

Expand source code
def encode_entity(self,
                  entity: Entity
                  ) -> Data:
    """Encode entity to data"""
    if self._encoding == Encoding.BER:
        return ber.encode_entity(entity)
    raise ValueError('invalid encoding')
def encode_value(self, module: str, name: str, value: typing.Union[ForwardRef('bool'), ForwardRef('int'), ForwardRef('BitString'), ForwardRef('bytes'), ForwardRef('Null'), ForwardRef('ObjectIdentifier'), ForwardRef('str'), ForwardRef('External'), ForwardRef('float'), ForwardRef('int'), ForwardRef('EmbeddedPDV'), ForwardRef('Choice'), ForwardRef('Set'), ForwardRef('SetOf'), ForwardRef('Sequence'), ForwardRef('SequenceOf'), ForwardRef('Entity')]) ‑> Entity

Encode value to entity

Expand source code
def encode_value(self,
                 module: str,
                 name: str,
                 value: Value
                 ) -> Entity:
    """Encode value to entity"""
    if self._encoding == Encoding.BER:
        return ber.encode_value(self._repository._refs,
                                common.TypeRef(module, name),
                                value)
    raise ValueError('invalid encoding')
class Encoding (value, names=None, *, module=None, qualname=None, type=None, start=1)

An enumeration.

Ancestors

  • enum.Enum

Class variables

var BER
class Entity

Encoding independent ASN.1 Entity

Expand source code
class Entity(abc.ABC):
    """Encoding independent ASN.1 Entity"""

Ancestors

  • abc.ABC
class External (data: typing.Union[ForwardRef('Entity'), bytes, bytearray, memoryview, typing.List[bool]], direct_ref: typing.Union[typing.List[typing.Union[int, typing.Tuple[strint]]], NoneType], indirect_ref: typing.Union[int, NoneType])

External(data, direct_ref, indirect_ref)

Expand source code
class External(typing.NamedTuple):
    data: typing.Union['Entity', Data, typing.List[bool]]
    direct_ref: typing.Optional[ObjectIdentifier]
    indirect_ref: typing.Optional[int]

Ancestors

  • builtins.tuple

Instance variables

var data : typing.Union[Entitybytes, bytearray, memoryview, typing.List[bool]]

Alias for field number 0

var direct_ref : typing.Union[typing.List[typing.Union[int, typing.Tuple[strint]]], NoneType]

Alias for field number 1

var indirect_ref : typing.Union[int, NoneType]

Alias for field number 2

class Repository (*args: typing.Union[pathlib.PurePath, str, ForwardRef('Repository')])

ASN.1 type definition repository.

Repository can be initialized with multiple arguments, which can be instances of pathlib.PurePath, str or Repository.

If an argument is of type pathlib.PurePath, and path points to file with a suffix '.asn', ASN.1 type definitions are decoded from the file. Otherwise, it is assumed that path points to a directory, which is recursively searched for ASN.1 definitions. All decoded types are added to the repository. Previously added type definitions with the same references are replaced.

If an argument is of type str, it represents ASN.1 type definitions. All decoded types are added to the repository. Previously added type definitions with the same references are replaced.

If an argument is of type Repository, its data definitions are added to the new repository. Previously added type definitions with the same references are replaced.

Expand source code
class Repository:
    """ASN.1 type definition repository.

    Repository can be initialized with multiple arguments, which can be
    instances of ``pathlib.PurePath``, ``str`` or ``Repository``.

    If an argument is of type ``pathlib.PurePath``, and path points to file
    with a suffix '.asn', ASN.1 type definitions are decoded from the file.
    Otherwise, it is assumed that path points to a directory,
    which is recursively searched for ASN.1 definitions. All decoded types
    are added to the repository. Previously added type definitions with the
    same references are replaced.

    If an argument is of type ``str``, it represents ASN.1 type definitions.
    All decoded types are added to the repository. Previously added type
    definitions with the same references are replaced.

    If an argument is of type ``Repository``, its data definitions are added to
    the new repository. Previously added type definitions with the
    same references are replaced.

    """

    def __init__(self, *args: typing.Union[pathlib.PurePath,
                                           str,
                                           'Repository']):
        self._refs = {}
        for arg in args:
            if isinstance(arg, pathlib.PurePath):
                self._load_path(arg)
            elif isinstance(arg, str):
                self._parse_asn1_def(arg)
            elif isinstance(arg, Repository):
                self._refs.update(arg._refs)
            else:
                raise ValueError('invalid argument')

    @staticmethod
    def from_json(data: typing.Union[pathlib.PurePath, json.Data]
                  ) -> 'Repository':
        """Create repository from JSON data representation"""
        if isinstance(data, pathlib.PurePath):
            data = json.decode_file(data)
        repo = Repository()
        repo._refs = {common.type_from_json(k): common.type_from_json(v)
                      for k, v in data}
        return repo

    def to_json(self) -> json.Data:
        """Represent repository as JSON data"""
        return [[common.type_to_json(k), common.type_to_json(v)]
                for k, v in self._refs.items()]

    def generate_html_doc(self) -> str:
        """Generate HTML documentation"""
        return doc.generate_html(self._refs)

    def _load_path(self, path):
        paths = [path] if path.suffix == '.asn' else path.rglob('*.asn')
        for path in paths:
            with open(path, 'r', encoding='utf-8') as f:
                asn1_def = f.read()
            self._parse_asn1_def(asn1_def)

    def _parse_asn1_def(self, asn1_def):
        from hat.asn1 import parser
        refs = parser.parse(asn1_def)
        self._refs.update(refs)

Static methods

def from_json(data: typing.Union[pathlib.PurePath, NoneType, boolintfloatstr, typing.List[ForwardRef('Data')], typing.Dict[str, ForwardRef('Data')]]) ‑> Repository

Create repository from JSON data representation

Expand source code
@staticmethod
def from_json(data: typing.Union[pathlib.PurePath, json.Data]
              ) -> 'Repository':
    """Create repository from JSON data representation"""
    if isinstance(data, pathlib.PurePath):
        data = json.decode_file(data)
    repo = Repository()
    repo._refs = {common.type_from_json(k): common.type_from_json(v)
                  for k, v in data}
    return repo

Methods

def generate_html_doc(self) ‑> str

Generate HTML documentation

Expand source code
def generate_html_doc(self) -> str:
    """Generate HTML documentation"""
    return doc.generate_html(self._refs)
def to_json(self) ‑> typing.Union[NoneType, boolintfloatstr, typing.List[typing.Union[bytes, bytearray, memoryview]], typing.Dict[str, typing.Union[bytes, bytearray, memoryview]]]

Represent repository as JSON data

Expand source code
def to_json(self) -> json.Data:
    """Represent repository as JSON data"""
    return [[common.type_to_json(k), common.type_to_json(v)]
            for k, v in self._refs.items()]
class Boolean (...)

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

Ancestors

  • builtins.int
class OctetString (...)

bytes(iterable_of_ints) -> bytes bytes(string, encoding[, errors]) -> bytes bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer bytes(int) -> bytes object of size given by the parameter initialized with null bytes bytes() -> empty bytes object

Construct an immutable array of bytes from: - an iterable yielding integers in range(256) - a text string encoded using the specified encoding - any object implementing the buffer API. - an integer

Static methods

def maketrans(frm, to, /)

Return a translation table useable for the bytes or bytearray translate method.

The returned table will be one where each byte in frm is mapped to the byte at the same position in to.

The bytes objects frm and to must be of the same length.

Methods

def capitalize(...)

B.capitalize() -> copy of B

Return a copy of B with only its first character capitalized (ASCII) and the rest lower-cased.

def center(self, width, fillchar=b' ', /)

Return a centered string of length width.

Padding is done using the specified fill character.

def count(...)

B.count(sub[, start[, end]]) -> int

Return the number of non-overlapping occurrences of subsection sub in bytes B[start:end]. Optional arguments start and end are interpreted as in slice notation.

def decode(self, /, encoding='utf-8', errors='strict')

Decode the bytes using the codec registered for encoding.

encoding The encoding with which to decode the bytes. errors The error handling scheme to use for the handling of decoding errors. The default is 'strict' meaning that decoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that can handle UnicodeDecodeErrors.

def endswith(...)

B.endswith(suffix[, start[, end]]) -> bool

Return True if B ends with the specified suffix, False otherwise. With optional start, test B beginning at that position. With optional end, stop comparing B at that position. suffix can also be a tuple of bytes to try.

def expandtabs(self, /, tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

def find(...)

B.find(sub[, start[, end]]) -> int

Return the lowest index in B where subsection sub is found, such that sub is contained within B[start,end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

def fromhex(string, /)

Create a bytes object from a string of hexadecimal numbers.

Spaces between two numbers are accepted. Example: bytes.fromhex('B9 01EF') -> b'\xb9\x01\xef'.

def hex(...)

Create a str of hexadecimal numbers from a bytes object.

sep An optional single character or byte to separate hex bytes. bytes_per_sep How many bytes between separators. Positive values count from the right, negative values count from the left.

Example:

>>> value = b'\xb9\x01\xef'
>>> value.hex()
'b901ef'
>>> value.hex(':')
'b9:01:ef'
>>> value.hex(':', 2)
'b9:01ef'
>>> value.hex(':', -2)
'b901:ef'
def index(...)

B.index(sub[, start[, end]]) -> int

Return the lowest index in B where subsection sub is found, such that sub is contained within B[start,end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the subsection is not found.

def isalnum(...)

B.isalnum() -> bool

Return True if all characters in B are alphanumeric and there is at least one character in B, False otherwise.

def isalpha(...)

B.isalpha() -> bool

Return True if all characters in B are alphabetic and there is at least one character in B, False otherwise.

def isascii(...)

B.isascii() -> bool

Return True if B is empty or all characters in B are ASCII, False otherwise.

def isdigit(...)

B.isdigit() -> bool

Return True if all characters in B are digits and there is at least one character in B, False otherwise.

def islower(...)

B.islower() -> bool

Return True if all cased characters in B are lowercase and there is at least one cased character in B, False otherwise.

def isspace(...)

B.isspace() -> bool

Return True if all characters in B are whitespace and there is at least one character in B, False otherwise.

def istitle(...)

B.istitle() -> bool

Return True if B is a titlecased string and there is at least one character in B, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.

def isupper(...)

B.isupper() -> bool

Return True if all cased characters in B are uppercase and there is at least one cased character in B, False otherwise.

def join(self, iterable_of_bytes, /)

Concatenate any number of bytes objects.

The bytes whose method is called is inserted in between each pair.

The result is returned as a new bytes object.

Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.

def ljust(self, width, fillchar=b' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character.

def lower(...)

B.lower() -> copy of B

Return a copy of B with all ASCII characters converted to lowercase.

def lstrip(self, bytes=None, /)

Strip leading bytes contained in the argument.

If the argument is omitted or None, strip leading ASCII whitespace.

def partition(self, sep, /)

Partition the bytes into three parts using the given separator.

This will search for the separator sep in the bytes. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original bytes object and two empty bytes objects.

def replace(self, old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

def rfind(...)

B.rfind(sub[, start[, end]]) -> int

Return the highest index in B where subsection sub is found, such that sub is contained within B[start,end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

def rindex(...)

B.rindex(sub[, start[, end]]) -> int

Return the highest index in B where subsection sub is found, such that sub is contained within B[start,end]. Optional arguments start and end are interpreted as in slice notation.

Raise ValueError when the subsection is not found.

def rjust(self, width, fillchar=b' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character.

def rpartition(self, sep, /)

Partition the bytes into three parts using the given separator.

This will search for the separator sep in the bytes, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty bytes objects and the original bytes object.

def rsplit(self, /, sep=None, maxsplit=-1)

Return a list of the sections in the bytes, using sep as the delimiter.

sep The delimiter according which to split the bytes. None (the default value) means split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

Splitting is done starting at the end of the bytes and working to the front.

def rstrip(self, bytes=None, /)

Strip trailing bytes contained in the argument.

If the argument is omitted or None, strip trailing ASCII whitespace.

def split(self, /, sep=None, maxsplit=-1)

Return a list of the sections in the bytes, using sep as the delimiter.

sep The delimiter according which to split the bytes. None (the default value) means split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

def splitlines(self, /, keepends=False)

Return a list of the lines in the bytes, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

def startswith(...)

B.startswith(prefix[, start[, end]]) -> bool

Return True if B starts with the specified prefix, False otherwise. With optional start, test B beginning at that position. With optional end, stop comparing B at that position. prefix can also be a tuple of bytes to try.

def strip(self, bytes=None, /)

Strip leading and trailing bytes contained in the argument.

If the argument is omitted or None, strip leading and trailing ASCII whitespace.

def swapcase(...)

B.swapcase() -> copy of B

Return a copy of B with uppercase ASCII characters converted to lowercase ASCII and vice versa.

def title(...)

B.title() -> copy of B

Return a titlecased version of B, i.e. ASCII words start with uppercase characters, all remaining cased characters have lowercase.

def translate(self, table, /, delete=b'')

Return a copy with each character mapped by the given translation table.

table Translation table, which must be a bytes object of length 256.

All characters occurring in the optional argument delete are removed. The remaining characters are mapped through the given translation table.

def upper(...)

B.upper() -> copy of B

Return a copy of B with all ASCII characters converted to uppercase.

def zfill(self, width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The original string is never truncated.

class Real (x=0, /)

Convert a string or number to a floating point number, if possible.

Instance variables

var imag

the imaginary part of a complex number

var real

the real part of a complex number

Methods

def as_integer_ratio(self, /)

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original float and with a positive denominator.

Raise OverflowError on infinities and a ValueError on NaNs.

>>> (10.0).as_integer_ratio()
(10, 1)
>>> (0.0).as_integer_ratio()
(0, 1)
>>> (-.25).as_integer_ratio()
(-1, 4)
def conjugate(self, /)

Return self, the complex conjugate of any float.

def fromhex(string, /)

Create a floating-point number from a hexadecimal string.

>>> float.fromhex('0x1.ffffp10')
2047.984375
>>> float.fromhex('-0x1p-1074')
-5e-324
def hex(self, /)

Return a hexadecimal representation of a floating-point number.

>>> (-0.1).hex()
'-0x1.999999999999ap-4'
>>> 3.14159.hex()
'0x1.921f9f01b866ep+1'
def is_integer(self, /)

Return True if the float is an integer.

class Integer (...)

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.

>>> int('0b100', base=0)
4

Subclasses

  • attr._make._CacheHashWrapper
  • builtins.bool
  • enum.IntEnum
  • enum.IntFlag
  • sre_constants._NamedIntConstant

Instance variables

var denominator

the denominator of a rational number in lowest terms

var imag

the imaginary part of a complex number

var numerator

the numerator of a rational number in lowest terms

var real

the real part of a complex number

Methods

def as_integer_ratio(self, /)

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
def bit_length(self, /)

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
def conjugate(...)

Returns self, the complex conjugate of any int.

def from_bytes(bytes, byteorder, *, signed=False)

Return the integer represented by the given array of bytes.

bytes Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Indicates whether two's complement is used to represent the integer.

def to_bytes(self, /, length, byteorder, *, signed=False)

Return an array of bytes representing an integer.

length Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

class Enumerated (...)

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.

>>> int('0b100', base=0)
4

Subclasses

  • attr._make._CacheHashWrapper
  • builtins.bool
  • enum.IntEnum
  • enum.IntFlag
  • sre_constants._NamedIntConstant

Instance variables

var denominator

the denominator of a rational number in lowest terms

var imag

the imaginary part of a complex number

var numerator

the numerator of a rational number in lowest terms

var real

the real part of a complex number

Methods

def as_integer_ratio(self, /)

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
def bit_length(self, /)

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
def conjugate(...)

Returns self, the complex conjugate of any int.

def from_bytes(bytes, byteorder, *, signed=False)

Return the integer represented by the given array of bytes.

bytes Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Indicates whether two's complement is used to represent the integer.

def to_bytes(self, /, length, byteorder, *, signed=False)

Return an array of bytes representing an integer.

length Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

class String (...)

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

Subclasses

  • aiohttp.payload.Order
  • docutils.nodes.Text
  • markdown.util.AtomicString
  • markupsafe.Markup
  • multidict._multidict.istr
  • pygments.lexer.include
  • shibokensupport.signature.mapping._NotCalled

Static methods

def maketrans(...)

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

Methods

def capitalize(self, /)

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

def casefold(self, /)

Return a version of the string suitable for caseless comparisons.

def center(self, width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

def count(...)

S.count(sub[, start[, end]]) -> int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

def encode(self, /, encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding The encoding in which to encode the string. errors The error handling scheme to use for encoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

def endswith(...)

S.endswith(suffix[, start[, end]]) -> bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

def expandtabs(self, /, tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

def find(...)

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

def format(...)

S.format(args, *kwargs) -> str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').

def format_map(...)

S.format_map(mapping) -> str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}').

def index(...)

S.index(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

def isalnum(self, /)

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

def isalpha(self, /)

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

def isascii(self, /)

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

def isdecimal(self, /)

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

def isdigit(self, /)

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

def isidentifier(self, /)

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as "def" or "class".

def islower(self, /)

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

def isnumeric(self, /)

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

def isprintable(self, /)

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

def isspace(self, /)

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

def istitle(self, /)

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

def isupper(self, /)

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

def join(self, iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

def ljust(self, width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

def lower(self, /)

Return a copy of the string converted to lowercase.

def lstrip(self, chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

def partition(self, sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

def replace(self, old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

def rfind(...)

S.rfind(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

def rindex(...)

S.rindex(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

def rjust(self, width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

def rpartition(self, sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

def rsplit(self, /, sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string.

sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

Splits are done starting at the end of the string and working to the front.

def rstrip(self, chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

def split(self, /, sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string.

sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

def splitlines(self, /, keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

def startswith(...)

S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

def strip(self, chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

def swapcase(self, /)

Convert uppercase characters to lowercase and lowercase characters to uppercase.

def title(self, /)

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

def translate(self, table, /)

Replace each character in the string using the given translation table.

table Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via getitem, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

def upper(self, /)

Return a copy of the string converted to uppercase.

def zfill(self, width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.