types - Common data types

Overview

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

Exceptions

Error

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

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

Singleton

class firebird.base.types.Singleton(*args, **kwargs)

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.

Sentinel

class firebird.base.types.Sentinel(name)

Bases: object

Simple sentinel object.

Important

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

name

Sentinel name.

Type

str

__repr__()

Returns Sentinel(‘name’)

__str__()

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.

Predefined sentinels

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

Sentinel that denotes default value

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

Sentinel that denotes infinity value

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

Sentinel that denotes unlimited value

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

Sentinel that denotes unknown value

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

Sentinel that denotes a condition when value was not found

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

Sentinel that denotes explicitly undefined value

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

Sentinel that denotes any value

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

Sentinel that denotes all possible values

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

Sentinel that denotes suspend request (in message queue)

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

Sentinel that denotes resume request (in message queue)

firebird.base.types.STOP: firebird.base.types.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 a 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

Distinct

class firebird.base.types.Distinct

Bases: abc.ABC

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

abstract get_key()

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

CachedDistinct

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

Bases: firebird.base.types.Distinct

Abstract Distinct descendant that caches instances.

All created instances are cached in WeakValueDictionary.

abstract classmethod extract_key(*args, **kwargs)

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

ByteOrder

class firebird.base.types.ByteOrder(value)

Bases: enum.Enum

Byte order for storing numbers in binary MemoryBuffer.

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

ZMQTransport

class firebird.base.types.ZMQTransport(value)

Bases: enum.IntEnum

ZeroMQ transport protocol

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

ZMQDomain

class firebird.base.types.ZMQDomain(value)

Bases: enum.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.

ZeroMQ address

class firebird.base.types.ZMQAddress(value: AnyStr)

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.

property address

Address

Return type

str

property domain

Address domain

Return type

ZMQDomain

property protocol

Transport protocol

Return type

ZMQTransport

MIME

class firebird.base.types.MIME(value: AnyStr)

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().

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

Supported MIME types

property mime_type

MIME type specification: <type>/<subtype>

Return type

str

property params

MIME parameters

Return type

Dict[str, str]

property subtype

MIME subtype

Return type

str

property type

MIME type

Return type

str

PyExpr

class firebird.base.types.PyExpr(value: str)

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.

get_callable(arguments='', namespace=None)

Returns expression as callable function ready for execution.

Parameters

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

Return type

Callable

property expr

Expression code ready to be appased to eval.

PyCode

class firebird.base.types.PyCode(value: str)

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.

property code

Python code ready to be appased to exec.

PyCallable

class firebird.base.types.PyCallable(value: str)

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.

Meta classes

SingletonMeta

class firebird.base.types.SingletonMeta

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.

SentinelMeta

class firebird.base.types.SentinelMeta

Bases: type

Metaclass for Sentinel.

CachedDistinctMeta

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

Bases: abc.ABCMeta

Metaclass for CachedDistinct.

Conjunctive

firebird.base.types.Conjunctive(name, bases, attrs)

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