Python types 模块,UnboundMethodType() 实例源码
我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用types.UnboundMethodType()。
def __init__(cls, name, bases, dictionary):
if type(cls.__init__) is UnboundMethodType:
initializer = cls.__init__
elif type(cls.__new__) is FunctionType:
initializer = cls.__new__
else:
# noinspection PyUnusedLocal
def initializer(self, *args, **kw): pass
# noinspection PyShadowingNames
@preserve_signature(initializer)
def instance_creator(cls, *args, **kw):
key = (args, tuple(sorted(kw.iteritems())))
try:
hash(key)
except TypeError:
raise TypeError('cannot have singletons for classes with unhashable arguments')
if key not in cls.__instances__:
cls.__instances__[key] = super(Singleton, cls).__call__(*args, **kw)
return cls.__instances__[key]
super(Singleton, cls).__init__(name, bases, dictionary)
cls.__instances__ = {}
cls.__instantiate__ = instance_creator.__get__(cls, type(cls)) # bind instance_creator to cls
def get_signature(obj, method_name):
method = getattr(obj, method_name)
# Eat self for unbound methods bc signature doesn't do it
if PY3:
if (inspect.isclass(obj) and
not inspect.ismethod(method) and
not isinstance(
obj.__dict__.get(method_name),
staticmethod)):
method = functools.partial(method, None)
else:
if (isinstance(method, types.UnboundMethodType) and
method.__self__ is None):
method = functools.partial(method, None)
try:
return signature(method)
except:
return None
def _get_func_repr(func):
if isinstance(func, types.MethodType):
return "{cls}.{func}".format(
cls=func.im_self.__class__,
func=func.im_func.__name__
)
elif isinstance(func, types.BuiltinMethodType):
if not func.__self__:
return "{func}".format(
func=func.__name__
)
else:
return "{type}.{func}".format(
type=func.__self__,
func=func.__name__
)
elif (isinstance(func, types.ObjectType) and hasattr(func, "__call__")) or\
isinstance(func, (types.FunctionType, types.BuiltinFunctionType,
types.ClassType, types.UnboundMethodType)):
return "{module}.{func}".format(
module=func.__module__,
func=func.__name__
)
else:
raise ValueError("func must be callable")
def _get_func_repr(func):
if isinstance(func, types.MethodType):
return "{cls}.{func}".format(
cls=func.im_self.__class__,
func=func.im_func.__name__
)
elif isinstance(func, types.BuiltinMethodType):
if not func.__self__:
return "{func}".format(
func=func.__name__
)
else:
return "{type}.{func}".format(
type=func.__self__,
func=func.__name__
)
elif (isinstance(func, types.ObjectType) and hasattr(func, "__call__")) or\
isinstance(func, (types.FunctionType, types.BuiltinFunctionType,
types.ClassType, types.UnboundMethodType)):
return "{module}.{func}".format(
module=func.__module__,
func=func.__name__
)
else:
raise ValueError("func must be callable")
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parent, obj = self._resolveName(name, module)
if type(obj) == types.ModuleType:
return self.loadTestsFromModule(obj)
elif (isinstance(obj, (type, types.ClassType)) and
issubclass(obj, unittest.TestCase)):
return self.loadTestsFromTestCase(obj)
elif (type(obj) == types.UnboundMethodType and
isinstance(parent, (type, types.ClassType)) and
issubclass(parent, unittest.TestCase)):
return self.loadSpecificTestFromTestCase(parent, obj.__name__)
elif isinstance(obj, unittest.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, unittest.TestSuite):
return test
elif isinstance(test, unittest.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def authenticate(func, c, expose_request=False):
"""
A decorator that facilitates authentication per method. Setting
C{expose_request} to C{True} will set the underlying request object (if
there is one), usually HTTP and set it to the first argument of the
authenticating callable. If there is no request object, the default is
C{None}.
@raise TypeError: C{func} and authenticator must be callable.
"""
if not python.callable(func):
raise TypeError('func must be callable')
if not python.callable(c):
raise TypeError('Authenticator must be callable')
attr = func
if isinstance(func, types.UnboundMethodType):
attr = func.im_func
if expose_request is True:
c = globals()['expose_request'](c)
setattr(attr, '_pyamf_authenticator', c)
return func
def expose_request(func):
"""
A decorator that adds an expose_request flag to the underlying callable.
@raise TypeError: C{func} must be callable.
"""
if not python.callable(func):
raise TypeError("func must be callable")
if isinstance(func, types.UnboundMethodType):
setattr(func.im_func, '_pyamf_expose_request', True)
else:
setattr(func, '_pyamf_expose_request', True)
return func
def preprocess(func, c, expose_request=False):
"""
A decorator that facilitates preprocessing per method. Setting
C{expose_request} to C{True} will set the underlying request object (if
there is one), usually HTTP and set it to the first argument of the
preprocessing callable. If there is no request object, the default is
C{None}.
@raise TypeError: C{func} and preprocessor must be callable.
"""
if not python.callable(func):
raise TypeError('func must be callable')
if not python.callable(c):
raise TypeError('Preprocessor must be callable')
attr = func
if isinstance(func, types.UnboundMethodType):
attr = func.im_func
if expose_request is True:
c = globals()['expose_request'](c)
setattr(attr, '_pyamf_preprocessor', c)
return func
def _r_ha(self, attr):
try:
attr = getattr(self.delegate or self,attr)
if type(attr) in (UnboundMethodType, MethodType, BuiltinMethodType):
return 1 # method
except:
pass
return 2 # attribute
def WrapMethods(cls, state):
for name, func in inspect.getmembers(cls):
# NOTE: This doesn't work in python 3? Types module is different
if isinstance(func, types.UnboundMethodType):
setattr(cls, name, TracedFunc(func, cls.__name__, state))
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy: raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if type(obj) == types.ModuleType:
return self.loadTestsFromModule(obj)
elif (isinstance(obj, class_types) and
issubclass(obj, TestCase)):
return self.loadTestsFromTestCase(obj)
elif type(obj) == types.UnboundMethodType:
return parent(obj.__name__)
elif isinstance(obj, TestSuite):
return obj
elif callable(obj):
test = obj()
if not isinstance(test, (TestCase, TestSuite)):
raise ValueError(
"calling %s returned %s, not a test" % (obj,test))
return test
else:
raise ValueError( "don't know how to make test from: %s" % obj)
def _get_func_repr(func):
"""
Gets a string representing a function object
"""
if isinstance(func, types.MethodType):
return "{cls}.{func}".format(
cls=func.im_self.__class__,
func=func.im_func.__name__
)
elif isinstance(func, types.BuiltinMethodType):
if not func.__self__:
return "{func}".format(
func=func.__name__
)
else:
return "{type}.{func}".format(
type=func.__self__,
func=func.__name__
)
elif (isinstance(func, types.ObjectType) and hasattr(func, "__call__")) or\
isinstance(func, (types.FunctionType, types.BuiltinFunctionType,
types.ClassType, types.UnboundMethodType)):
return "{module}.{func}".format(
module=func.__module__,
func=func.__name__
)
else:
raise ValueError("func must be callable")
def _curry_callable(obj, *args, **kwargs):
"""Takes a callable and arguments and returns a task queue tuple.
The returned tuple consists of (callable, args, kwargs), and can be pickled
and unpickled safely.
Args:
obj: The callable to curry. See the module docstring for restrictions.
args: Positional arguments to call the callable with.
kwargs: Keyword arguments to call the callable with.
Returns:
A tuple consisting of (callable, args, kwargs) that can be evaluated by
run() with equivalent effect of executing the function directly.
Raises:
ValueError: If the passed in object is not of a valid callable type.
"""
if isinstance(obj, types.MethodType):
return (invoke_member, (obj.im_self, obj.im_func.__name__) + args, kwargs)
elif isinstance(obj, types.BuiltinMethodType):
if not obj.__self__:
return (obj, args, kwargs)
else:
return (invoke_member, (obj.__self__, obj.__name__) + args, kwargs)
elif isinstance(obj, types.ObjectType) and hasattr(obj, "__call__"):
return (obj, args, kwargs)
elif isinstance(obj, (types.FunctionType, types.BuiltinFunctionType,
types.ClassType, types.UnboundMethodType)):
return (obj, args, kwargs)
else:
raise ValueError("obj must be callable")
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, case.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, case.TestCase)):
return self.suiteClass([parent(obj.__name__)])
elif isinstance(obj, suite.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, suite.TestSuite):
return test
elif isinstance(test, case.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, case.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, case.TestCase)):
name = parts[-1]
inst = parent(name)
return self.suiteClass([inst])
elif isinstance(obj, suite.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, suite.TestSuite):
return test
elif isinstance(test, case.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, unittest.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, unittest.TestCase)):
name = obj.__name__
inst = parent(name)
# static methods follow a different path
if not isinstance(getattr(inst, name), types.FunctionType):
return self.suiteClass([inst])
elif isinstance(obj, unittest.TestSuite):
return obj
if hasattr(obj, '__call__'):
test = obj()
if isinstance(test, unittest.TestSuite):
return test
elif isinstance(test, unittest.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, case.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, case.TestCase)):
name = parts[-1]
inst = parent(name)
return self.suiteClass([inst])
elif isinstance(obj, suite.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, suite.TestSuite):
return test
elif isinstance(test, case.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, case.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, case.TestCase)):
name = parts[-1]
inst = parent(name)
return self.suiteClass([inst])
elif isinstance(obj, suite.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, suite.TestSuite):
return test
elif isinstance(test, case.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, case.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, case.TestCase)):
name = parts[-1]
inst = parent(name)
return self.suiteClass([inst])
elif isinstance(obj, suite.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, suite.TestSuite):
return test
elif isinstance(test, case.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, case.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, case.TestCase)):
name = parts[-1]
inst = parent(name)
return self.suiteClass([inst])
elif isinstance(obj, suite.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, suite.TestSuite):
return test
elif isinstance(test, case.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, case.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, case.TestCase)):
name = parts[-1]
inst = parent(name)
return self.suiteClass([inst])
elif isinstance(obj, suite.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, suite.TestSuite):
return test
elif isinstance(test, case.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
unused_parts = []
if module is None:
if not parts:
raise ValueError("incomplete test name: %s" % name)
else:
parts_copy = parts[:]
while parts_copy:
target = ".".join(parts_copy)
if target in sys.modules:
module = reload(sys.modules[target])
parts = unused_parts
break
else:
try:
module = __import__(target)
parts = unused_parts
break
except ImportError:
unused_parts.insert(0, parts_copy[-1])
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
obj = getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif (((six.PY3 and isinstance(obj, type))
or isinstance(obj, (type, types.ClassType)))
and issubclass(obj, unittest.TestCase)):
return self.loadTestsFromTestCase(obj)
elif isinstance(obj, types.UnboundMethodType):
if six.PY3:
return obj.__self__.__class__(obj.__name__)
else:
return obj.im_class(obj.__name__)
elif hasattr(obj, '__call__'):
test = obj()
if not isinstance(test, unittest.TestCase) and \
not isinstance(test, unittest.TestSuite):
raise ValueError("calling %s returned %s, "
"not a test" % (obj, test))
return test
else:
raise ValueError("do not know how to make test from: %s" % obj)