summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/util/langhelpers.py
diff options
context:
space:
mode:
Diffstat (limited to 'lib/sqlalchemy/util/langhelpers.py')
-rw-r--r--lib/sqlalchemy/util/langhelpers.py157
1 files changed, 75 insertions, 82 deletions
diff --git a/lib/sqlalchemy/util/langhelpers.py b/lib/sqlalchemy/util/langhelpers.py
index d82aefdea..b0ff5b073 100644
--- a/lib/sqlalchemy/util/langhelpers.py
+++ b/lib/sqlalchemy/util/langhelpers.py
@@ -15,16 +15,14 @@ import re
import sys
import types
import warnings
-from .compat import set_types, threading, \
- callable, inspect_getfullargspec
from functools import update_wrapper
from .. import exc
import hashlib
from . import compat
def md5_hex(x):
- # Py3K
- #x = x.encode('utf-8')
+ if compat.py3k:
+ x = x.encode('utf-8')
m = hashlib.md5()
m.update(x)
return m.hexdigest()
@@ -77,8 +75,8 @@ def _unique_symbols(used, *bases):
used = set(used)
for base in bases:
pool = itertools.chain((base,),
- itertools.imap(lambda i: base + str(i),
- xrange(1000)))
+ compat.itertools_imap(lambda i: base + str(i),
+ range(1000)))
for sym in pool:
if sym not in used:
used.add(sym)
@@ -94,8 +92,8 @@ def decorator(target):
def decorate(fn):
if not inspect.isfunction(fn):
raise Exception("not a decoratable function")
- spec = inspect_getfullargspec(fn)
- names = tuple(spec[0]) + spec[1:3] + (fn.func_name,)
+ spec = compat.inspect_getfullargspec(fn)
+ names = tuple(spec[0]) + spec[1:3] + (fn.__name__,)
targ_name, fn_name = _unique_symbols(names, 'target', 'fn')
metadata = dict(target=targ_name, fn=fn_name)
@@ -104,7 +102,7 @@ def decorator(target):
code = 'lambda %(args)s: %(target)s(%(fn)s, %(apply_kw)s)' % (
metadata)
decorated = eval(code, {targ_name: target, fn_name: fn})
- decorated.func_defaults = getattr(fn, 'im_func', fn).func_defaults
+ decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
return update_wrapper(decorated, fn)
return update_wrapper(decorate, target)
@@ -143,7 +141,7 @@ class PluginLoader(object):
def register(self, name, modulepath, objname):
def load():
- mod = __import__(modulepath)
+ mod = compat.import_(modulepath)
for token in modulepath.split(".")[1:]:
mod = getattr(mod, token)
return getattr(mod, objname)
@@ -169,7 +167,7 @@ def get_cls_kwargs(cls, _set=None):
ctr = cls.__dict__.get('__init__', False)
has_init = ctr and isinstance(ctr, types.FunctionType) and \
- isinstance(ctr.func_code, types.CodeType)
+ isinstance(ctr.__code__, types.CodeType)
if has_init:
names, has_kw = inspect_func_args(ctr)
@@ -192,7 +190,7 @@ try:
from inspect import CO_VARKEYWORDS
def inspect_func_args(fn):
- co = fn.func_code
+ co = fn.__code__
nargs = co.co_argcount
names = co.co_varnames
args = list(names[:nargs])
@@ -248,8 +246,8 @@ def format_argspec_plus(fn, grouped=True):
'apply_pos': '(self, a, b, c, **d)'}
"""
- if callable(fn):
- spec = inspect_getfullargspec(fn)
+ if compat.callable(fn):
+ spec = compat.inspect_getfullargspec(fn)
else:
# we accept an existing argspec...
spec = fn
@@ -261,22 +259,21 @@ def format_argspec_plus(fn, grouped=True):
else:
self_arg = None
- # Py3K
- #apply_pos = inspect.formatargspec(spec[0], spec[1],
- # spec[2], None, spec[4])
- #num_defaults = 0
- #if spec[3]:
- # num_defaults += len(spec[3])
- #if spec[4]:
- # num_defaults += len(spec[4])
- #name_args = spec[0] + spec[4]
- # Py2K
- apply_pos = inspect.formatargspec(spec[0], spec[1], spec[2])
- num_defaults = 0
- if spec[3]:
- num_defaults += len(spec[3])
- name_args = spec[0]
- # end Py2K
+ if compat.py3k:
+ apply_pos = inspect.formatargspec(spec[0], spec[1],
+ spec[2], None, spec[4])
+ num_defaults = 0
+ if spec[3]:
+ num_defaults += len(spec[3])
+ if spec[4]:
+ num_defaults += len(spec[4])
+ name_args = spec[0] + spec[4]
+ else:
+ apply_pos = inspect.formatargspec(spec[0], spec[1], spec[2])
+ num_defaults = 0
+ if spec[3]:
+ num_defaults += len(spec[3])
+ name_args = spec[0]
if num_defaults:
defaulted_vals = name_args[0 - num_defaults:]
@@ -339,8 +336,8 @@ def unbound_method_to_callable(func_or_cls):
"""
- if isinstance(func_or_cls, types.MethodType) and not func_or_cls.im_self:
- return func_or_cls.im_func
+ if isinstance(func_or_cls, types.MethodType) and not func_or_cls.__self__:
+ return func_or_cls.__func__
else:
return func_or_cls
@@ -397,7 +394,7 @@ class portable_instancemethod(object):
"""
def __init__(self, meth):
- self.target = meth.im_self
+ self.target = meth.__self__
self.name = meth.__name__
def __call__(self, *arg, **kw):
@@ -417,32 +414,33 @@ def class_hierarchy(cls):
will not be descended.
"""
- # Py2K
- if isinstance(cls, types.ClassType):
- return list()
- # end Py2K
+ if compat.py2k:
+ if isinstance(cls, types.ClassType):
+ return list()
+
hier = set([cls])
process = list(cls.__mro__)
while process:
c = process.pop()
- # Py2K
- if isinstance(c, types.ClassType):
- continue
- for b in (_ for _ in c.__bases__
- if _ not in hier and not isinstance(_, types.ClassType)):
- # end Py2K
- # Py3K
- #for b in (_ for _ in c.__bases__
- # if _ not in hier):
+ if compat.py2k:
+ if isinstance(c, types.ClassType):
+ continue
+ bases = (_ for _ in c.__bases__
+ if _ not in hier and not isinstance(_, types.ClassType))
+ else:
+ bases = (_ for _ in c.__bases__ if _ not in hier)
+
+ for b in bases:
process.append(b)
hier.add(b)
- # Py3K
- #if c.__module__ == 'builtins' or not hasattr(c, '__subclasses__'):
- # continue
- # Py2K
- if c.__module__ == '__builtin__' or not hasattr(c, '__subclasses__'):
- continue
- # end Py2K
+
+ if compat.py3k:
+ if c.__module__ == 'builtins' or not hasattr(c, '__subclasses__'):
+ continue
+ else:
+ if c.__module__ == '__builtin__' or not hasattr(c, '__subclasses__'):
+ continue
+
for s in [_ for _ in c.__subclasses__() if _ not in hier]:
process.append(s)
hier.add(s)
@@ -499,9 +497,9 @@ def monkeypatch_proxied_specials(into_cls, from_cls, skip=None, only=None,
"return %(name)s.%(method)s%(d_args)s" % locals())
env = from_instance is not None and {name: from_instance} or {}
- exec py in env
+ compat.exec_(py, env)
try:
- env[method].func_defaults = fn.func_defaults
+ env[method].__defaults__ = fn.__defaults__
except AttributeError:
pass
setattr(into_cls, method, env[method])
@@ -510,11 +508,7 @@ def monkeypatch_proxied_specials(into_cls, from_cls, skip=None, only=None,
def methods_equivalent(meth1, meth2):
"""Return True if the two methods are the same implementation."""
- # Py3K
- #return getattr(meth1, '__func__', meth1) is getattr(meth2, '__func__', meth2)
- # Py2K
- return getattr(meth1, 'im_func', meth1) is getattr(meth2, 'im_func', meth2)
- # end Py2K
+ return getattr(meth1, '__func__', meth1) is getattr(meth2, '__func__', meth2)
def as_interface(obj, cls=None, methods=None, required=None):
@@ -587,7 +581,7 @@ def as_interface(obj, cls=None, methods=None, required=None):
for method, impl in dictlike_iteritems(obj):
if method not in interface:
raise TypeError("%r: unknown in this interface" % method)
- if not callable(impl):
+ if not compat.callable(impl):
raise TypeError("%r=%r is not callable" % (method, impl))
setattr(AnonymousInterface, method, staticmethod(impl))
found.add(method)
@@ -728,11 +722,11 @@ class importlater(object):
def _resolve(self):
importlater._unresolved.discard(self)
if self._il_addtl:
- self._initial_import = __import__(
+ self._initial_import = compat.import_(
self._il_path, globals(), locals(),
[self._il_addtl])
else:
- self._initial_import = __import__(self._il_path)
+ self._initial_import = compat.import_(self._il_path)
def __getattr__(self, key):
if key == 'module':
@@ -751,7 +745,7 @@ class importlater(object):
# from paste.deploy.converters
def asbool(obj):
- if isinstance(obj, (str, unicode)):
+ if isinstance(obj, compat.string_types):
obj = obj.strip().lower()
if obj in ['true', 'yes', 'on', 'y', 't', '1']:
return True
@@ -811,14 +805,14 @@ def constructor_copy(obj, cls, **kw):
def counter():
"""Return a threadsafe counter function."""
- lock = threading.Lock()
- counter = itertools.count(1L)
+ lock = compat.threading.Lock()
+ counter = itertools.count(1)
# avoid the 2to3 "next" transformation...
def _next():
lock.acquire()
try:
- return counter.next()
+ return next(counter)
finally:
lock.release()
@@ -834,7 +828,7 @@ def duck_type_collection(specimen, default=None):
if hasattr(specimen, '__emulates__'):
# canonicalize set vs sets.Set to a standard: the builtin set
if (specimen.__emulates__ is not None and
- issubclass(specimen.__emulates__, set_types)):
+ issubclass(specimen.__emulates__, set)):
return set
else:
return specimen.__emulates__
@@ -842,7 +836,7 @@ def duck_type_collection(specimen, default=None):
isa = isinstance(specimen, type) and issubclass or isinstance
if isa(specimen, list):
return list
- elif isa(specimen, set_types):
+ elif isa(specimen, set):
return set
elif isa(specimen, dict):
return dict
@@ -874,15 +868,14 @@ def assert_arg_type(arg, argtype, name):
def dictlike_iteritems(dictlike):
"""Return a (key, value) iterator for almost any dict-like object."""
- # Py3K
- #if hasattr(dictlike, 'items'):
- # return dictlike.items()
- # Py2K
- if hasattr(dictlike, 'iteritems'):
- return dictlike.iteritems()
- elif hasattr(dictlike, 'items'):
- return iter(dictlike.items())
- # end Py2K
+ if compat.py3k:
+ if hasattr(dictlike, 'items'):
+ return list(dictlike.items())
+ else:
+ if hasattr(dictlike, 'iteritems'):
+ return dictlike.iteritems()
+ elif hasattr(dictlike, 'items'):
+ return iter(dictlike.items())
getter = getattr(dictlike, '__getitem__', getattr(dictlike, 'get', None))
if getter is None:
@@ -891,7 +884,7 @@ def dictlike_iteritems(dictlike):
if hasattr(dictlike, 'iterkeys'):
def iterator():
- for key in dictlike.iterkeys():
+ for key in dictlike.keys():
yield key, getter(key)
return iterator()
elif hasattr(dictlike, 'keys'):
@@ -935,7 +928,7 @@ class hybridmethod(object):
class _symbol(int):
def __new__(self, name, doc=None, canonical=None):
"""Construct a new named symbol."""
- assert isinstance(name, str)
+ assert isinstance(name, compat.string_types)
if canonical is None:
canonical = hash(name)
v = int.__new__(_symbol, canonical)
@@ -978,7 +971,7 @@ class symbol(object):
"""
symbols = {}
- _lock = threading.Lock()
+ _lock = compat.threading.Lock()
def __new__(cls, name, doc=None, canonical=None):
cls._lock.acquire()
@@ -1032,7 +1025,7 @@ def warn(msg, stacklevel=3):
be controlled.
"""
- if isinstance(msg, basestring):
+ if isinstance(msg, compat.string_types):
warnings.warn(msg, exc.SAWarning, stacklevel=stacklevel)
else:
warnings.warn(msg, stacklevel=stacklevel)