SQLAlchemy 0.5 Documentation

Multiple Pages | One Page
Version: 0.5.0rc4 Last Updated: 11/14/08 16:38:11

module sqlalchemy.util

Module Functions

def accepts_a_list_as_starargs(list_deprecation=None)
def 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.
def asbool(obj)
def assert_arg_type(arg, argtype, name)
def 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.

def 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.

def decode_slice(slc)

decode a slice object as sent to __getitem__.

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

def decorator(target)

A signature-matching decorator factory.

def 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.
def dictlike_iteritems(dictlike)

Return a (key, value) iterator for almost any dict-like object.

def 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.

def flatten_iterator(x)

Given an iterator of which further sub-elements may also be iterators, flatten the sub-elements into a single iterator.

def 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)
def 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)'}
def 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.

def 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.

def get_func_kwargs(func)

Return the full set of legal kwargs for the given func.

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

def 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.

def 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.
def reset_memoized(instance, name)
def 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).

def to_list(x, default=None)
def to_set(x)
def unbound_method_to_callable(func_or_cls)

Adjust the incoming callable such that a 'self' argument is not required.

def unique_list(seq, compare_with=)
def unique_symbols(used, *bases)
def update_wrapper(wrapper, wrapped, assigned=('__module__', '__name__', '__doc__'), updated=('__dict__',))

Update a wrapper function to look like the wrapped function

wrapper is the function to be updated wrapped is the original function assigned is a tuple naming the attributes assigned directly from the wrapped function to the wrapper function (defaults to functools.WRAPPER_ASSIGNMENTS) updated is a tuple naming the attributes off the wrapper that are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES)

def warn(msg)
def warn_deprecated(msg)
def warn_exception(func, *args, **kwargs)

executes the given function, catches all exceptions and converts to a warning.

def warn_pending_deprecation(msg)

class IdentitySet(object)

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.

def __init__(self, iterable=None)

Construct a new IdentitySet.

def add(self, value)
def clear(self)
def copy(self)
def __copy__(self)
def difference(self, iterable)
def difference_update(self, iterable)
def discard(self, value)
def intersection(self, iterable)
def intersection_update(self, iterable)
def issubset(self, iterable)
def issuperset(self, iterable)
def pop(self)
def remove(self, value)
def symmetric_difference(self, iterable)
def symmetric_difference_update(self, iterable)
def union(self, iterable)
def update(self, iterable)
def __and__(self, other)
def __cmp__(self, other)
def __contains__(self, value)
def __eq__(self, other)
def __ge__(self, other)
def __gt__(self, other)
def __iand__(self, other)
def __ior__(self, other)
def __isub__(self, other)
def __iter__(self)
def __ixor__(self, other)
def __le__(self, other)
def __len__(self)
def __lt__(self, other)
def __ne__(self, other)
def __or__(self, other)
def __sub__(self, other)
def __xor__(self, other)
back to section top

class OrderedDict(dict)

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

def __init__(self, _OrderedDict____sequence=None, **kwargs)

Construct a new OrderedDict.

def clear(self)
def items(self)
def iteritems(self)
def iterkeys(self)
def itervalues(self)
def keys(self)
def pop(self, key, *default)
def popitem(self)
def setdefault(self, key, value)
def sort(self, *arg, **kw)
def update(self, _OrderedDict____sequence=None, **kwargs)
def values(self)
def __delitem__(self, key)
def __iter__(self)
def __setitem__(self, key, object)
back to section top

class OrderedIdentitySet(IdentitySet)

def __init__(self, iterable=None)

Construct a new OrderedIdentitySet.

back to section top

class OrderedProperties(object)

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

def __init__(self)

Construct a new OrderedProperties.

def clear(self)
def get(self, key, default=None)
def has_key(self, key)
def keys(self)
def update(self, value)
def __add__(self, other)
def __contains__(self, key)
def __delitem__(self, key)
def __getattr__(self, key)
def __getitem__(self, key)
def __iter__(self)
def __len__(self)
def __setattr__(self, key, object)
def __setitem__(self, key, object)
back to section top

class OrderedSet(set)

def __init__(self, d=None)

Construct a new OrderedSet.

def add(self, element)
def clear(self)
def __sub__(self, other)
def difference(self, other)
def __isub__(self, other)
def difference_update(self, other)
def discard(self, element)
def insert(self, pos, element)
def __and__(self, other)
def intersection(self, other)
def __iand__(self, other)
def intersection_update(self, other)
def remove(self, element)
def symmetric_difference(self, other)
def __xor__(self, other)
def symmetric_difference_update(self, other)
def __ixor__(self, other)
def __or__(self, other)
def union(self, other)
def update(self, iterable)
def __ior__(self, iterable)
def __getitem__(self, key)
def __iter__(self)
back to section top

class PopulateDict(dict)

A dict which populates missing values via a creation function.

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

def __init__(self, creator)

Construct a new PopulateDict.

def __missing__(self, key)
back to section top

class ScopedRegistry(object)

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. If None, ScopedRegistry uses a threading.local object instead.
def __init__(self, createfunc, scopefunc)

Construct a new ScopedRegistry.

def clear(self)
def has(self)
def set(self, obj)
def __call__(self)
back to section top

class UniqueAppender(object)

Appends items to a collection ensuring uniqueness.

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

def __init__(self, data, via=None)

Construct a new UniqueAppender.

def append(self, item)
def __iter__(self)
back to section top

class WeakCompositeKey(object)

an weak-referencable, hashable collection which is strongly referenced until any one of its members is garbage collected.

def __init__(self, *args)

Construct a new WeakCompositeKey.

args = property()
def __cmp__(self, other)
def __iter__(self)
back to section top

class 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.

def __init__(self)

Construct a new WeakIdentityMapping.

def clear(self)
def pop(self, object, default=)
def popitem(self)
def setdefault(self, object, default=None)
def update(self, *a, **kw)
def __delitem__(self, object)
def __setitem__(self, object, value)
back to section top

class defaultdict(dict)

defaultdict(default_factory) --> dict with default factory

The default factory is called without arguments to produce a new value when a key is not present, in __getitem__ only. A defaultdict compares equal to a dict with the same items.

default_factory = property()

Factory for default value called by __missing__().

back to section top

class memoized_instancemethod(object)

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.

def __init__(self, fget, doc=None)

Construct a new memoized_instancemethod.

def __get__(self, obj, cls)
back to section top

class memoized_property(object)

A read-only @property that is only evaluated once.

def __init__(self, fget, doc=None)

Construct a new memoized_property.

def __get__(self, obj, cls)
back to section top

class symbol(object)

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.

back to section top

class symbol(object)

def __init__(self, name)

Construct a new named symbol.

back to section top
Up: API Documentation | Previous: module sqlalchemy.types | Next: module sqlalchemy.orm