types - Common data types

Overview

This module provides collection of classes that are often used by other library modules or applications.

Exceptions

exception firebird.base.types.Error(*args, **kwargs)[source]

Bases: Exception

Exception that is intended to be used as a base class of all application-related errors. The important difference from Exception class is that Error accepts keyword arguments, that are stored into instance attributes with the same name.

Important

Attribute lookup on this class never fails, as all attributes that are not actually set, have None value.

Example:

try:
    if condition:
        raise Error("Error message", err_code=1)
    else:
        raise Error("Unknown error")
except Error as e:
    if e.err_code is None:
        ...
    elif e.err_code == 1:
        ...

Note

Warnings are not considered errors and thus should not use this class as base.

Singletons

Singleton is a pattern that restricts the instantiation of a class to one “single” instance. This is useful when exactly one object is needed to coordinate actions across the system.

Common uses:

  • The abstract factory, factory method, builder, and prototype patterns can use singletons in their implementation.

  • Facade objects are often singletons because only one facade object is required.

  • State objects are often singletons.

  • Singletons are often preferred to global variables because:

    • They do not pollute the global namespace with unnecessary variables.

    • They permit lazy allocation and initialization.

To create your own singletons, use Singleton as the base class.

example

>>> class MySingleton(Singleton):
...     "Description"
...     ...
...
>>> obj1 = MySingleton()
>>> obj1 = MySingleton()
>>> obj1 is obj2
True
class firebird.base.types.Singleton(*args, **kwargs)[source]

Bases: object

Base class for singletons.

Important

If you create a descendant class that uses constructor arguments, these arguments are meaningful ONLY on first call, because all subsequent calls simply return an instance stored in cache without calling the constructor.

Sentinels

The Sentinel Object pattern is a standard Pythonic approach that’s used both in the Standard Library and beyond. The pattern most often uses Python’s built-in None object, but in situations where None might be a useful value, a unique sentinel object() can be used instead to indicate missing or unspecified data, or other specific condition.

However, the plain object() sentinel has not very useful str and repr values. The Sentinel class provides named sentinels, with meaningful str and repr.


class firebird.base.types.Sentinel(*args, **kwargs)[source]

Bases: object

Simple sentinel object.

Important

All sentinels have name, that is always in capital letters. Sentinels with the same name are singletons.

__init__(name: str)[source]
Parameters

name (str) – Sentinel name.

__repr__()[source]

Returns Sentinel(‘name’).

__str__()[source]

Returns name.

instances = {'ALL': Sentinel('ALL'), 'ANY': Sentinel('ANY'), 'DEFAULT': Sentinel('DEFAULT'), 'INFINITY': Sentinel('INFINITY'), 'NOT_FOUND': Sentinel('NOT_FOUND'), 'RESUME': Sentinel('RESUME'), 'STOP': Sentinel('STOP'), 'SUSPEND': Sentinel('SUSPEND'), 'UNDEFINED': Sentinel('UNDEFINED'), 'UNKNOWN': Sentinel('UNKNOWN'), 'UNLIMITED': Sentinel('UNLIMITED')}

Class attribute with defined sentinels. There is no need to access or manipulate it.

name

Sentinel name.

Predefined sentinels

firebird.base.types.DEFAULT: Sentinel = Sentinel('DEFAULT')

Sentinel that denotes default value

firebird.base.types.INFINITY: Sentinel = Sentinel('INFINITY')

Sentinel that denotes infinity value

firebird.base.types.UNLIMITED: Sentinel = Sentinel('UNLIMITED')

Sentinel that denotes unlimited value

firebird.base.types.UNKNOWN: Sentinel = Sentinel('UNKNOWN')

Sentinel that denotes unknown value

firebird.base.types.NOT_FOUND: Sentinel = Sentinel('NOT_FOUND')

Sentinel that denotes a condition when value was not found

firebird.base.types.UNDEFINED: Sentinel = Sentinel('UNDEFINED')

Sentinel that denotes explicitly undefined value

firebird.base.types.ANY: Sentinel = Sentinel('ANY')

Sentinel that denotes any value

firebird.base.types.ALL: Sentinel = Sentinel('ALL')

Sentinel that denotes all possible values

firebird.base.types.SUSPEND: Sentinel = Sentinel('SUSPEND')

Sentinel that denotes suspend request (in message queue)

firebird.base.types.RESUME: Sentinel = Sentinel('RESUME')

Sentinel that denotes resume request (in message queue)

firebird.base.types.STOP: Sentinel = Sentinel('STOP')

Sentinel that denotes stop request (in message queue)

Distinct objects

Some complex data structures or data processing algorithms require unique object identification (ie object identity). In Python, an object identity is defined internally as unique instance identity that is not suitable for complex objects whose identity is derived from content.

The Distinct abstract base class is intended as a unified solution to these needs.

See also

module firebird.base.collections


class firebird.base.types.Distinct[source]

Bases: ABC

Abstract base class for classes (incl. dataclasses) with distinct instances.

abstract get_key() Hashable[source]

Returns instance key.

Important

The key is used for instance hash computation that by default uses the hash function. If the key is not suitable argument for hash, you must provide your own __hash__ implementation as well!

Return type

Hashable


class firebird.base.types.CachedDistinct(*args, **kwargs)[source]

Bases: Distinct

Abstract Distinct descendant that caches instances.

All created instances are cached in WeakValueDictionary.

abstract classmethod extract_key(*args, **kwargs) Hashable[source]

Returns key from arguments passed to __init__().

Important

The key is used to store instance in cache. It should be the same as key returned by instance Distinct.get_key()!

Return type

Hashable

Enums

class firebird.base.types.ByteOrder(value)[source]

Bases: Enum

Byte order for storing numbers in binary MemoryBuffer.

BIG = 'big'
LITTLE = 'little'
NETWORK = 'big'

class firebird.base.types.ZMQTransport(value)[source]

Bases: IntEnum

ZeroMQ transport protocol.

EPGM = 5
INPROC = 1
IPC = 2
PGM = 4
TCP = 3
UNKNOWN = 0
VMCI = 6

class firebird.base.types.ZMQDomain(value)[source]

Bases: IntEnum

ZeroMQ address domain.

LOCAL = 1
NETWORK = 3
NODE = 2
UNKNOWN = 0

Custom string types

Some string values have unified structure and carry specific information (like network address or database connection string). Typical repeating operation with these values are validation and parsing. It makes sense to put these operations under one roof. One such approach uses custom descendants of builtin str type.

Caution

Custom string types have an inherent weakness. They support all inherited string methods, but any method that returns string value return a base str type, not the decendant class type. That same apply when you assign strings to variables that should be of custom string type.

Tip

Module strconv could help you to safely translate strings stored externally to typed strings.


class firebird.base.types.ZMQAddress(value: AnyStr)[source]

Bases: str

ZeroMQ endpoint address.

It behaves like str, but checks that value is valid ZMQ endpoint address, has additional R/O properties and meaningful repr().

Raises

ValueError – When string value passed to constructor is not a valid ZMQ endpoint address.

Parameters

value (AnyStr) –

property address: str

Endpoint address.

property domain: ZMQDomain

Endpoint address domain.

property protocol: ZMQTransport

Transport protocol.


class firebird.base.types.MIME(value: AnyStr)[source]

Bases: str

MIME type specification.

It behaves like str, but checks that value is valid MIME type specification, has additional R/O properties and meaningful repr().

Parameters

value (AnyStr) –

MIME_TYPES = ['text', 'image', 'audio', 'video', 'application', 'multipart', 'message']

Supported MIME types

property mime_type: str

<type>/<subtype>.

Type

MIME type specification

property params: Dict[str, str]

MIME parameters.

property subtype: str

MIME subtype.

property type: str

MIME type.


class firebird.base.types.PyExpr(value: str)[source]

Bases: str

Source code for Python expression.

It behaves like str, but checks that value is a valid Python expression, and provides direct access to compiled code.

Raises

SyntaxError – When string value is not a valid Python expression.

Parameters

value (str) –

get_callable(arguments: str = '', namespace: Optional[Dict[str, Any]] = None) Callable[source]

Returns expression as callable function ready for execution.

Parameters
  • arguments (str) – String with arguments (names separated by coma) for returned function.

  • namespace (Optional[Dict[str, Any]]) – Dictionary with namespace elements available for expression.

Return type

Callable

property expr

Expression code ready to be appased to eval.


class firebird.base.types.PyCode(value: str)[source]

Bases: str

Python source code.

It behaves like str, but checks that value is a valid Python code block, and provides direct access to compiled code.

Raises

SyntaxError – When string value is not a valid Python code block.

Parameters

value (str) –

property code

Python code ready to be appased to exec.


class firebird.base.types.PyCallable(value: str)[source]

Bases: str

Source code for Python callable.

It behaves like str, but checks that value is a valid Python callable (function of class definition), and acts like a callable (i.e. you can directly call the PyCallable value).

Raises
  • ValueError – When string value does not contains the function or class definition.

  • SyntaxError – When string value is not a valid Python callable.

Parameters

value (str) –

name: str = None

Name of the callable (function).

Meta classes

class firebird.base.types.SingletonMeta[source]

Bases: type

Metaclass for Singleton classes.

Manages internal cache of class instances. If instance for a class is in cache, it’s returned without calling the constructor, otherwise the instance is created normally and stored in cache for later use.


class firebird.base.types.SentinelMeta[source]

Bases: type

Metaclass for Sentinel.


class firebird.base.types.CachedDistinctMeta(name, bases, namespace, **kwargs)[source]

Bases: ABCMeta

Metaclass for CachedDistinct.


firebird.base.types.Conjunctive(name, bases, attrs)[source]

Returns a metaclass that is conjunctive descendant of all metaclasses used by parent classes.

Example

class A(type): pass

class B(type): pass

class AA(metaclass=A):pass

class BB(metaclass=B):pass

class CC(AA, BB, metaclass=Conjunctive): pass

Functions

firebird.base.types.load(spec: str) Any[source]

Return object from module. Module is imported if necessary.

Parameters

spec (str) – Object specification in format module[.submodule...]:object_name[.object_name...]

Return type

Any