SQLAlchemy 0.6.1 Documentation

Version: 0.6.1 Last Updated: 07/25/2016 21:14:41
API Reference | Index

Utilities

class sqlalchemy.util.IdentitySet(iterable=None)

A set that considers only object id() for uniqueness.

This strategy has edge cases for builtin types- it’s possible to have two ‘foo’ strings in one of these sets, for example. Use sparingly.

__init__(iterable=None)
class sqlalchemy.util.LRUCache(capacity=100, threshold=0.5)

Dictionary with ‘squishy’ removal of least recently used items.

__init__(capacity=100, threshold=0.5)
class sqlalchemy.util.NamedTuple

tuple() subclass that adds labeled names.

Is also pickleable.

class sqlalchemy.util.OrderedDict(_OrderedDict____sequence=None, **kwargs)

A dict that returns keys/values/items in the order they were added.

__init__(_OrderedDict____sequence=None, **kwargs)
class sqlalchemy.util.OrderedProperties

An object that maintains the order in which attributes are set upon it.

Also provides an iterator and a very basic getitem/setitem interface to those attributes.

(Not really a dict, since it iterates over values, not keys. Not really a list, either, since each value must have a key associated; hence there is no append or extend.)

__init__()
class sqlalchemy.util.PopulateDict(creator)

A dict which populates missing values via a creation function.

Note the creation function takes a key, unlike collections.defaultdict.

__init__(creator)
class sqlalchemy.util.ScopedRegistry(createfunc, scopefunc)

A Registry that can store one or multiple instances of a single class on a per-thread scoped basis, or on a customized scope.

createfunc
a callable that returns a new object to be placed in the registry
scopefunc
a callable that will return a key to store/retrieve an object.
__init__(createfunc, scopefunc)
class sqlalchemy.util.UniqueAppender(data, via=None)

Appends items to a collection ensuring uniqueness.

Additional appends() of the same object are ignored. Membership is determined by identity (is a) not equality (==).

__init__(data, via=None)
class sqlalchemy.util.WeakIdentityMapping

A WeakKeyDictionary with an object identity index.

Adds a .by_id dictionary to a regular WeakKeyDictionary. Trades performance during mutation operations for accelerated lookups by id().

The usual cautions about weak dictionaries and iteration also apply to this subclass.

__init__()
sqlalchemy.util.as_interface(obj, cls=None, methods=None, required=None)

Ensure basic interface compliance for an instance or dict of callables.

Checks that obj implements public methods of cls or has members listed in methods. If required is not supplied, implementing at least one interface method is sufficient. Methods present on obj that are not in the interface are ignored.

If obj is a dict and dict does not meet the interface requirements, the keys of the dictionary are inspected. Keys present in obj that are not in the interface will raise TypeErrors.

Raises TypeError if obj does not meet the interface criteria.

In all passing cases, an object with callable members is returned. In the simple case, obj is returned as-is; if dict processing kicks in then an anonymous class is returned.

obj
A type, instance, or dictionary of callables.
cls
Optional, a type. All public methods of cls are considered the interface. An obj instance of cls will always pass, ignoring required..
methods
Optional, a sequence of method names to consider as the interface.
required
Optional, a sequence of mandatory implementations. If omitted, an obj that provides at least one interface method is considered sufficient. As a convenience, required may be a type, in which case all public methods of the type are required.
sqlalchemy.util.class_hierarchy(cls)

Return an unordered sequence of all classes related to cls.

Traverses diamond hierarchies.

Fibs slightly: subclasses of builtin types are not returned. Thus class_hierarchy(class A(object)) returns (A, object), not A plus every class systemwide that derives from object.

Old-style classes are discarded and hierarchies rooted on them will not be descended.

sqlalchemy.util.classproperty

A decorator that behaves like @property except that operates on classes rather than instances.

This is helpful when you need to compute __table_args__ and/or __mapper_args__ when using declarative.

sqlalchemy.util.coerce_kw_type(kw, key, type_, flexi_bool=True)
If ‘key’ is present in dict ‘kw’, coerce its value to type ‘type_’ if necessary. If ‘flexi_bool’ is True, the string ‘0’ is considered false when coercing to boolean.
sqlalchemy.util.decode_slice(slc)

decode a slice object as sent to __getitem__.

takes into account the 2.5 __index__() method, basically.

sqlalchemy.util.decorator(target)
A signature-matching decorator factory.
sqlalchemy.util.deprecated(message=None, add_deprecation_to_docstring=True)

Decorates a function and issues a deprecation warning on use.

message
If provided, issue message in the warning. A sensible default is used if not provided.
add_deprecation_to_docstring
Default True. If False, the wrapped function’s __doc__ is left as-is. If True, the ‘message’ is prepended to the docs if provided, or sensible default if message is omitted.
sqlalchemy.util.dictlike_iteritems(dictlike)
Return a (key, value) iterator for almost any dict-like object.
sqlalchemy.util.duck_type_collection(specimen, default=None)
Given an instance or class, guess if it is or is acting as one of the basic collection types: list, set and dict. If the __emulates__ property is present, return that preferentially.
sqlalchemy.util.flatten_iterator(x)
Given an iterator of which further sub-elements may also be iterators, flatten the sub-elements into a single iterator.
sqlalchemy.util.format_argspec_init(method, grouped=True)

format_argspec_plus with considerations for typical __init__ methods

Wraps format_argspec_plus with error handling strategies for typical __init__ cases:

object.__init__ -> (self)
other unreflectable (usually C) -> (self, *args, **kwargs)
sqlalchemy.util.format_argspec_plus(fn, grouped=True)

Returns a dictionary of formatted, introspected function arguments.

A enhanced variant of inspect.formatargspec to support code generation.

fn
An inspectable callable or tuple of inspect getargspec() results.
grouped
Defaults to True; include (parens, around, argument) lists

Returns:

args
Full inspect.formatargspec for fn
self_arg
The name of the first positional argument, varargs[0], or None if the function defines no positional arguments.
apply_pos
args, re-written in calling rather than receiving syntax. Arguments are passed positionally.
apply_kw
Like apply_pos, except keyword-ish args are passed as keywords.

Example:

>>> format_argspec_plus(lambda self, a, b, c=3, **d: 123)
{'args': '(self, a, b, c=3, **d)',
 'self_arg': 'self',
 'apply_kw': '(self, a, b, c=c, **d)',
 'apply_pos': '(self, a, b, c, **d)'}
sqlalchemy.util.function_named(fn, name)

Return a function with a given __name__.

Will assign to __name__ and return the original function if possible on the Python implementation, otherwise a new function will be constructed.

sqlalchemy.util.get_cls_kwargs(cls)

Return the full set of inherited kwargs for the given cls.

Probes a class’s __init__ method, collecting all named arguments. If the __init__ defines a **kwargs catch-all, then the constructor is presumed to pass along unrecognized keywords to it’s base classes, and the collection process is repeated recursively on each of the bases.

sqlalchemy.util.get_func_kwargs(func)
Return the full set of legal kwargs for the given func.
sqlalchemy.util.getargspec_init(method)

inspect.getargspec with considerations for typical __init__ methods

Wraps inspect.getargspec with error handling for typical __init__ cases:

object.__init__ -> (self)
other unreflectable (usually C) -> (self, *args, **kwargs)
sqlalchemy.util.iterate_attributes(cls)

iterate all the keys and attributes associated with a class, without using getattr().

Does not use getattr() so that class-sensitive descriptors (i.e. property.__get__()) are not called.

sqlalchemy.util.memoized_instancemethod

Decorate a method memoize its return value.

Best applied to no-arg methods: memoization is not sensitive to argument values, and will always return the same value even when called with different arguments.

sqlalchemy.util.memoized_property
A read-only @property that is only evaluated once.
sqlalchemy.util.monkeypatch_proxied_specials(into_cls, from_cls, skip=None, only=None, name='self.proxy', from_instance=None)
Automates delegation of __specials__ for a proxying type.
sqlalchemy.util.pending_deprecation(version, message=None, add_deprecation_to_docstring=True)

Decorates a function and issues a pending deprecation warning on use.

version
An approximate future version at which point the pending deprecation will become deprecated. Not used in messaging.
message
If provided, issue message in the warning. A sensible default is used if not provided.
add_deprecation_to_docstring
Default True. If False, the wrapped function’s __doc__ is left as-is. If True, the ‘message’ is prepended to the docs if provided, or sensible default if message is omitted.
sqlalchemy.util.populate_column_dict
alias of PopulateDict
class sqlalchemy.util.portable_instancemethod(meth)

Turn an instancemethod into a (parent, name) pair to produce a serializable callable.

__init__(meth)
sqlalchemy.util.set_creation_order(instance)

Assign a ‘_creation_order’ sequence to the given instance.

This allows multiple instances to be sorted in order of creation (typically within a single thread; the counter is not particularly threadsafe).

class sqlalchemy.util.symbol

A constant symbol.

>>> symbol('foo') is symbol('foo')
True
>>> symbol('foo')
<symbol 'foo>

A slight refinement of the MAGICCOOKIE=object() pattern. The primary advantage of symbol() is its repr(). They are also singletons.

Repeated calls of symbol(‘name’) will all return the same instance.

sqlalchemy.util.unbound_method_to_callable(func_or_cls)
Adjust the incoming callable such that a ‘self’ argument is not required.
sqlalchemy.util.update_copy(d, _new=None, **kw)
Copy the given dict and update with the given values.
sqlalchemy.util.warn_exception(func, *args, **kwargs)
executes the given function, catches all exceptions and converts to a warning.
Previous: Interfaces Next: sqlalchemy.orm