本文整理汇总了Python中six.get_method_self函数的典型用法代码示例。如果您正苦于以下问题:Python get_method_self函数的具体用法?Python get_method_self怎么用?Python get_method_self使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_method_self函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_add_testcase_info
def test_add_testcase_info(self, mock_methods):
# Build a fake runner
test_case = TestCase()
runner = TestRunner(test_case)
# Populate runner with fake structure
runner.unittests = {}
runner.unittests['mod class.sample_method1'] = True
runner.unittests['mod class.sample_method2'] = False
runner.unittests['mod class.sample_method3'] = True
# Populate fake test_case with 3 fake methods
self1_t = type(six.get_method_self(self.sample_method1))
self2_t = type(six.get_method_self(self.sample_method2))
self3_t = type(six.get_method_self(self.sample_method3))
self1_t.__name__ = self2_t.__name__ = self3_t.__name__ = 'class'
self1_t.__module__ = self2_t.__module__ = self3_t.__module__ = 'mod'
test_methods = [self.sample_method1, self.sample_method2, self.sample_method3]
# Run add_testcase_info
mock_methods.return_value = test_methods
add_testcase_info(test_case, runner)
# Verify that unittests work
suites1 = getattr(self.sample_method1.__func__, '_suites', [])
self.assertEqual('unittest' in suites1, True)
suites2 = getattr(self.sample_method2.__func__, '_suites', [])
self.assertEqual('unittest' not in suites2, True)
self.assertEqual('test_suite' in suites2, True)
suites3 = getattr(self.sample_method3.__func__, '_suites', [])
self.assertEqual('unittest' in suites3, True)
开发者ID:chriskuehl,项目名称:Testify,代码行数:32,代码来源:unittest_annotate_test.py
示例2: upgrade_websocket
def upgrade_websocket(self, environ, start_response):
"""
Attempt to upgrade the socket environ['wsgi.input'] into a websocket enabled connection.
"""
websocket_version = environ.get('HTTP_SEC_WEBSOCKET_VERSION', '')
if not websocket_version:
raise UpgradeRequiredError
elif websocket_version not in self.WS_VERSIONS:
raise HandshakeError('Unsupported WebSocket Version: {0}'.format(websocket_version))
key = environ.get('HTTP_SEC_WEBSOCKET_KEY', '').strip()
if not key:
raise HandshakeError('Sec-WebSocket-Key header is missing/empty')
try:
key_len = len(base64.b64decode(key))
except TypeError:
raise HandshakeError('Invalid key: {0}'.format(key))
if key_len != 16:
# 5.2.1 (3)
raise HandshakeError('Invalid key: {0}'.format(key))
sec_ws_accept = base64.b64encode(sha1(six.b(key) + self.WS_GUID).digest())
if six.PY3:
sec_ws_accept = sec_ws_accept.decode('ascii')
headers = [
('Upgrade', 'websocket'),
('Connection', 'Upgrade'),
('Sec-WebSocket-Accept', sec_ws_accept),
('Sec-WebSocket-Version', str(websocket_version)),
]
logger.debug('WebSocket request accepted, switching protocols')
start_response(force_str('101 Switching Protocols'), headers)
six.get_method_self(start_response).finish_content()
return WebSocket(environ['wsgi.input'])
开发者ID:dalou,项目名称:django-workon,代码行数:34,代码来源:django_runserver.py
示例3: save_instancemethod0
def save_instancemethod0(pickler, obj): # example: cStringIO.StringI
log.info("Me: %s" % obj) # XXX: obj.__dict__ handled elsewhere?
args = (get_method_function(obj), get_method_self(obj)) if PY3 \
else (get_method_function(obj), get_method_self(obj), obj.im_class)
pickler.save_reduce(MethodType, args, obj=obj)
log.info("# Me")
开发者ID:wxiang7,项目名称:dill,代码行数:9,代码来源:dill.py
示例4: _prepare_mw
def _prepare_mw(middleware=None):
"""Check middleware interface and prepare it to iterate.
Args:
middleware: list (or object) of input middleware
Returns:
A middleware list
"""
if middleware is None:
middleware = []
else:
if not isinstance(middleware, list):
middleware = [middleware]
# check basic interface of middleware objects
for mw in middleware:
if not hasattr(mw, 'process_request') and not\
hasattr(mw, 'process_response'):
raise TypeError('{0} is not a valid middlware'.format(str(mw)))
# Check process_request and process_response are bounded methods
for mw_method in ('process_request', 'process_response'):
method_mw_bound = getattr(mw, mw_method, None)
if method_mw_bound is not None:
if six.get_method_self(method_mw_bound) is None:
raise AttributeError(
'{0} must be a bound method'.format(method_mw_bound))\
# pragma: no cover
return middleware
开发者ID:TheSriram,项目名称:falcon,代码行数:34,代码来源:api.py
示例5: get_function_path
def get_function_path(function, bound_to=None):
"""Get received function path (as string), to import function later
with `import_string`.
"""
if isinstance(function, six.string_types):
return function
# static and class methods
if hasattr(function, '__func__'):
real_function = function.__func__
elif callable(function):
real_function = function
else:
return function
func_path = []
module = getattr(real_function, '__module__', '__main__')
if module:
func_path.append(module)
if not bound_to:
try:
bound_to = six.get_method_self(function)
except AttributeError:
pass
if bound_to:
if isinstance(bound_to, six.class_types):
func_path.append(bound_to.__name__)
else:
func_path.append(bound_to.__class__.__name__)
func_path.append(real_function.__name__)
return '.'.join(func_path)
开发者ID:pombredanne,项目名称:easy_cache,代码行数:35,代码来源:utils.py
示例6: get_bound_method
def get_bound_method(obj, method_name):
"""Get a bound method of the given object by name.
Args:
obj: Object on which to look up the method.
method_name: Name of the method to retrieve.
Returns:
Bound method, or ``None`` if the method does not exist on
the object.
Raises:
AttributeError: The method exists, but it isn't
bound (most likely a class was passed, rather than
an instance of that class).
"""
method = getattr(obj, method_name, None)
if method is not None:
# NOTE(kgriffs): Ensure it is a bound method
if six.get_method_self(method) is None:
# NOTE(kgriffs): In Python 3 this code is unreachable
# because the above will raise AttributeError on its
# own.
msg = '{0} must be a bound method'.format(method)
raise AttributeError(msg)
return method
开发者ID:balsagoth,项目名称:jasmin,代码行数:29,代码来源:misc.py
示例7: get_method_self
def get_method_self(method):
if not inspect.ismethod(method):
return None
try:
return six.get_method_self(method)
except AttributeError:
return None
开发者ID:celttechie,项目名称:taskflow,代码行数:7,代码来源:reflection.py
示例8: test_get_method_self
def test_get_method_self():
class X(object):
def m(self):
pass
x = X()
assert six.get_method_self(x.m) is x
py.test.raises(AttributeError, six.get_method_self, 42)
开发者ID:A-Maze,项目名称:A-Pc,代码行数:7,代码来源:test_six.py
示例9: find_ctx
def find_ctx(elt):
"""Get the right ctx related to input elt.
In order to keep safe memory as much as possible, it is important to find
the right context element. For example, instead of putting properties on
a function at the level of an instance, it is important to save such
property on the instance because the function.__dict__ is shared with
instance class function, and so, if the instance is deleted from memory,
the property is still present in the class memory. And so on, it is
impossible to identify the right context in such case if all properties
are saved with the same key in the same function which is the function.
"""
result = elt # by default, result is ctx
# if elt is ctx and elt is a method, it is possible to find the best ctx
if ismethod(elt):
# get instance and class of the elt
instance = get_method_self(elt)
# if instance is not None, the right context is the instance
if instance is not None:
result = instance
elif PY2:
result = elt.im_class
return result
开发者ID:b3j0f,项目名称:utils,代码行数:27,代码来源:property.py
示例10: to_dict
def to_dict(self):
test_method_self_t = type(six.get_method_self(self.test_method))
assert not isinstance(test_method_self_t, type(None))
return {
"previous_run": self.previous_run,
"start_time": time.mktime(self.start_time.timetuple()) if self.start_time else None,
"end_time": time.mktime(self.end_time.timetuple()) if self.end_time else None,
"run_time": (self.run_time.seconds + float(self.run_time.microseconds) / 1000000)
if self.run_time is not None
else None,
"normalized_run_time": None
if not self.run_time
else "%.2fs" % (self.run_time.seconds + (self.run_time.microseconds / 1000000.0)),
"complete": self.complete,
"success": self.success,
"failure": self.failure,
"error": self.error,
"interrupted": self.interrupted,
"exception_info": self.format_exception_info(),
"exception_info_pretty": self.format_exception_info(pretty=True),
"exception_only": self.format_exception_only(),
"runner_id": self.runner_id,
"method": {
"module": test_method_self_t.__module__,
"class": test_method_self_t.__name__,
"name": self.test_method.__name__,
"full_name": "%s %s.%s"
% (test_method_self_t.__module__, test_method_self_t.__name__, self.test_method.__name__),
"fixture_type": None
if not inspection.is_fixture_method(self.test_method)
else self.test_method._fixture_type,
},
}
开发者ID:chriskuehl,项目名称:Testify,代码行数:33,代码来源:test_result.py
示例11: validate_args
def validate_args(fn, *args, **kwargs):
"""Check that the supplied args are sufficient for calling a function.
>>> validate_args(lambda a: None)
Traceback (most recent call last):
...
MissingArgs: Missing argument(s): a
>>> validate_args(lambda a, b, c, d: None, 0, c=1)
Traceback (most recent call last):
...
MissingArgs: Missing argument(s): b, d
:param fn: the function to check
:param arg: the positional arguments supplied
:param kwargs: the keyword arguments supplied
"""
argspec = inspect.getargspec(fn)
num_defaults = len(argspec.defaults or [])
required_args = argspec.args[:len(argspec.args) - num_defaults]
if six.get_method_self(fn) is not None:
required_args.pop(0)
missing = [arg for arg in required_args if arg not in kwargs]
missing = missing[len(args):]
return missing
开发者ID:biruce-openstack,项目名称:nova,代码行数:27,代码来源:utils.py
示例12: ensure_generator
def ensure_generator(self, fixture):
if fixture._fixture_type in HYBRID_FIXTURES:
# already a context manager, nothing to do
return fixture
if fixture._fixture_type in SETUP_FIXTURES:
def wrapper(self):
fixture()
yield
elif fixture._fixture_type in TEARDOWN_FIXTURES:
def wrapper(self):
yield
fixture()
wrapper.__name__ = fixture.__name__
wrapper.__doc__ = fixture.__doc__
wrapper._fixture_type = fixture._fixture_type
wrapper._fixture_id = fixture._fixture_id
wrapper._defining_class_depth = fixture._defining_class_depth
# http://stackoverflow.com/q/4364565
func_self = six.get_method_self(fixture)
assert func_self is not None
return wrapper.__get__(func_self, type(func_self))
开发者ID:Yelp,项目名称:Testify,代码行数:27,代码来源:test_fixtures.py
示例13: clear_api_path_map_cache
def clear_api_path_map_cache(self):
"""Clear out cache for api_path_map."""
self._api_path_cache = None
for api_provider in self.api_providers:
if six.get_method_self(
api_provider.clear_api_path_map_cache,
) is not None:
api_provider.clear_api_path_map_cache()
开发者ID:acemaster,项目名称:django-ddp,代码行数:8,代码来源:api.py
示例14: get_method_self
def get_method_self(method):
"""Gets the ``self`` object attached to this method (or none)."""
if not inspect.ismethod(method):
return None
try:
return six.get_method_self(method)
except AttributeError:
return None
开发者ID:sjsucohort6,项目名称:openstack,代码行数:8,代码来源:reflection.py
示例15: key_names
def key_names(self):
# If the current page has a last_evaluated_key, use it to determine key attributes
if self._last_evaluated_key:
return self._last_evaluated_key.keys()
# Use the table meta data to determine the key attributes
table_meta = six.get_method_self(self._operation).get_meta_table() # type: ignore # method_self cannot be None
return table_meta.get_key_names(self._kwargs.get('index_name'))
开发者ID:jlafon,项目名称:PynamoDB,代码行数:8,代码来源:pagination.py
示例16: runiter
def runiter(self, slot_name, **kwargs):
"""Return an iterable of PluginHookRunner objects.
The iterable will return a PluginHookRunner object
for each plugin hook mapped to slot_name. Multiple plugins
with hooks for the same slot will result in multiple
PluginHookRunners in the iterable.
See run() docs for what to expect from PluginHookRunner.run().
"""
# slot's called should always exist here, if not
if slot_name not in self._slot_to_funcs:
raise SlotNameException(slot_name)
for func in self._slot_to_funcs[slot_name]:
module = inspect.getmodule(func)
func_module_name = getattr(func, '__module__')
if not func_module_name:
if module:
func_module_name = module.__name__
else:
func_module_name = 'unknown_module'
func_class_name = six.get_method_self(func).__class__.__name__
plugin_key = ".".join([func_module_name, func_class_name])
log.debug("Running %s in %s" % (six.get_method_function(func).__name__, plugin_key))
# resolve slot_name to conduit
# FIXME: handle cases where we don't have a conduit for a slot_name
# (should be able to handle this since we map those at the same time)
conduit = self._slot_to_conduit[slot_name]
try:
# create a Conduit
# FIXME: handle cases where we can't create a Conduit()
conduit_instance = conduit(six.get_method_self(func).__class__, **kwargs)
# TypeError tends to mean we provided the wrong kwargs for this
# conduit
# if we get an Exception above, should we exit early, or
# continue onto other hooks. A conduit could fail for
# something specific to func.__class__, but unlikely
except Exception as e:
log.exception(e)
raise
runner = PluginHookRunner(conduit_instance, func)
yield runner
开发者ID:Januson,项目名称:subscription-manager,代码行数:45,代码来源:plugins.py
示例17: process_request
def process_request(request):
for method in self.methods['process_request']:
response = yield method(request=request, spider=spider)
assert response is None or isinstance(response, (Response, Request)), \
'Middleware %s.process_request must return None, Response or Request, got %s' % \
(six.get_method_self(method).__class__.__name__, response.__class__.__name__)
if response:
defer.returnValue(response)
defer.returnValue((yield download_func(request=request,spider=spider)))
开发者ID:01-,项目名称:scrapy,代码行数:9,代码来源:middleware.py
示例18: _find_method
def _find_method(obj, func):
if obj:
try:
func_self = six.get_method_self(func)
except AttributeError: # func has no __self__
pass
else:
if func_self is obj:
return six.get_method_function(func).__name__
raise ValueError("Function %s is not a method of: %s" % (func, obj))
开发者ID:fighting-one-piece,项目名称:repository-python,代码行数:10,代码来源:mobileonlinescheduler.py
示例19: process_exception
def process_exception(_failure):
exception = _failure.value
for method in self.methods['process_exception']:
response = yield method(request=request, exception=exception, spider=spider)
if response is not None and not isinstance(response, (Response, Request)):
raise _InvalidOutput('Middleware %s.process_exception must return None, Response or Request, got %s' % \
(six.get_method_self(method).__class__.__name__, type(response)))
if response:
defer.returnValue(response)
defer.returnValue(_failure)
开发者ID:elacuesta,项目名称:scrapy,代码行数:10,代码来源:middleware.py
示例20: process_exception
def process_exception(_failure):
exception = _failure.value
for method in self.methods['process_exception']:
response = method(request=request, exception=exception, spider=spider)
assert response is None or isinstance(response, (Response, Request)), \
'Middleware %s.process_exception must return None, Response or Request, got %s' % \
(six.get_method_self(method).__class__.__name__, type(response))
if response:
return response
return _failure
开发者ID:cdingding,项目名称:scrapy,代码行数:10,代码来源:middleware.py
注:本文中的six.get_method_self函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论