本文整理汇总了Python中callable函数的典型用法代码示例。如果您正苦于以下问题:Python callable函数的具体用法?Python callable怎么用?Python callable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了callable函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: collect_files
def collect_files():
if callable(custom_files):
try:
files = custom_files()
if files:
return files
except:
_logger.exception("Error while trying to retrieve tracked files for plugin {}".format(key))
templates = _get_all_templates()
assets = _get_all_assets()
translations = _get_all_translationfiles(g.locale.language if g.locale else "en",
"messages")
files = templates + assets + translations
if callable(additional_files):
try:
af = additional_files()
if af:
files += af
except:
_logger.exception("Error while trying to retrieve additional tracked files for plugin {}".format(key))
return sorted(set(files))
示例2: get_callable
def get_callable(lookup_view, can_fail=False):
"""
Convert a string version of a function name to the callable object.
If the lookup_view is not an import path, it is assumed to be a URL pattern
label and the original string is returned.
If can_fail is True, lookup_view might be a URL pattern label, so errors
during the import fail and the string is returned.
"""
if not callable(lookup_view):
try:
# Bail early for non-ASCII strings (they can't be functions).
lookup_view = lookup_view.encode('ascii')
mod_name, func_name = get_mod_func(lookup_view)
if func_name != '':
lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name)
if not callable(lookup_view):
raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name))
except (ImportError, AttributeError):
if not can_fail:
raise
except UnicodeEncodeError:
pass
return lookup_view
示例3: lookup_field
def lookup_field(name, obj, model_admin=None):
opts = obj._meta
try:
f = opts.get_field(name)
except models.FieldDoesNotExist:
# For non-field values, the value is either a method, property or
# returned via a callable.
if callable(name):
attr = name
value = attr(obj)
elif (model_admin is not None and hasattr(model_admin, name) and
not name == '__str__' and not name == '__unicode__'):
attr = getattr(model_admin, name)
value = attr(obj)
else:
if is_rel_field(name,obj):
parts = name.split("__")
rel_name,sub_rel_name = parts[0],"__".join(parts[1:])
rel_obj = getattr(obj,rel_name)
if rel_obj is not None:
return lookup_field(sub_rel_name,rel_obj,model_admin)
attr = getattr(obj, name)
if callable(attr):
value = attr()
else:
value = attr
f = None
else:
attr = None
value = getattr(obj, name)
return f, attr, value
示例4: get_form_cfg
def get_form_cfg(self, req, moddef, section, value=None):
if self.read_cap and not req.has_permission(self.read_cap):
return None
field_name = '.'.join((moddef, section.name, self.name))
loc = req.localizer
if callable(self.field_cfg):
cfg = self.field_cfg(req, moddef, section, value)
else:
cfg = self.field_cfg.copy()
cfg.update({
'name' : field_name,
'fieldLabel' : loc.translate(self.title) if self.title else self.name,
'description' : loc.translate(self.help_text) if self.help_text else None
})
if value is None and self.default is not None:
value = self.default
if value is not None and self.client_ok:
cfg['value'] = self.format_param(value)
if self.type == 'bool':
cfg['checked'] = value
extra = self.field_extra
if extra:
if callable(extra):
extra = extra(req, moddef, section, value)
cfg.update(extra)
return cfg
示例5: register_action
def register_action(self, event_name, action_object, *args, **kwargs):
action_name = str(action_object)
if ismethod(action_object) and callable(action_object):
action_object = SingleAction(action_object, *args, **kwargs)
elif isfunction(action_object) and callable(action_object):
action_object = SingleAction(action_object, *args, **kwargs)
elif not isinstance(action_object, SingleAction):
action_object = SingleAction.from_string(action_object)
if action_object is None:
logger.error('action_object is None')
return False
if 'single_fire_action' in kwargs.keys() and kwargs['single_fire_action'] is True:
action_object.single_fire_action = True
del kwargs['single_fire_action']
if event_name in self.__Actions.keys():
self.__Actions[event_name][action_name] = action_object
logger.trace("action %s was added to event %s", action_object, event_name)
else:
self.__Actions[event_name] = { action_name: action_object }
logger.trace("action %s was added to new evententry %s", action_object, event_name)
return action_object
示例6: lookup_field
def lookup_field(name, obj, model_admin=None):
opts = obj._meta
try:
f = _get_non_gfk_field(opts, name)
except (FieldDoesNotExist, FieldIsAForeignKeyColumnName):
# For non-field values, the value is either a method, property or
# returned via a callable.
if callable(name):
attr = name
value = attr(obj)
elif (model_admin is not None and
hasattr(model_admin, name) and
not name == '__str__' and
not name == '__unicode__'):
attr = getattr(model_admin, name)
value = attr(obj)
else:
attr = getattr(obj, name)
if callable(attr):
value = attr()
else:
value = attr
f = None
else:
attr = None
value = getattr(obj, name)
return f, attr, value
示例7: dispatch
def dispatch(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
if (self.response and not isinstance(self.response, HttpResponse)
and not callable(self.response)):
raise TypeError("The `response` keyword argument must "
"be a either HttpResponse instance or "
"callable with `request` argument")
if self.request.method == self.method:
key = self.cache_key()
if cache.get(key):
if callable(self.response):
return self.response(request)
elif self.response:
return self.response
else:
return HttpResponseForbidden('Try slowing down a little.')
cache.set(key, 1, self.duration)
return super(ThrottleMixin, self).dispatch(request, *args, **kwargs)
示例8: preprocess
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 callable(func):
raise TypeError('func must be callable')
if not 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
示例9: assertRaisesErrorWithMessage
def assertRaisesErrorWithMessage(self, error, message, callable,
*args, **kwargs):
self.assertRaises(error, callable, *args, **kwargs)
try:
callable(*args, **kwargs)
except error, e:
self.assertEqual(message, str(e))
示例10: __init__
def __init__(self, stmt="pass", setup="pass", timer=default_timer):
"""Constructor. See class doc string."""
self.timer = timer
ns = {}
if isinstance(stmt, str):
# Check that the code can be compiled outside a function
if isinstance(setup, str):
compile(setup, dummy_src_name, "exec")
compile(setup + '\n' + stmt, dummy_src_name, "exec")
else:
compile(stmt, dummy_src_name, "exec")
stmt = reindent(stmt, 8)
if isinstance(setup, str):
setup = reindent(setup, 4)
src = template.format(stmt=stmt, setup=setup)
elif callable(setup):
src = template.format(stmt=stmt, setup='_setup()')
ns['_setup'] = setup
else:
raise ValueError("setup is neither a string nor callable")
self.src = src # Save for traceback display
code = compile(src, dummy_src_name, "exec")
exec(code, globals(), ns)
self.inner = ns["inner"]
elif callable(stmt):
self.src = None
if isinstance(setup, str):
_setup = setup
def setup():
exec(_setup, globals(), ns)
elif not callable(setup):
raise ValueError("setup is neither a string nor callable")
self.inner = _template_func(setup, stmt)
else:
raise ValueError("stmt is neither a string nor callable")
示例11: instance_cache_key
def instance_cache_key(instance, label=None, version=None, args=None,
kwargs=None):
"""Extends the base `cache_key` function to include model instance metadata
such as the type and primary key. In addition the `version` can be a
property or method name on the instance which will be evaluated.
"""
if not instance or not instance.pk:
raise ValueError('model instances must have a primary key')
# The version may be an attribute on the instance
if isinstance(version, basestring) and hasattr(instance, version):
version = getattr(instance, version)
# Bound method
if callable(version):
version = version()
# Plain function takes the instance
elif callable(version):
version = version(instance)
opts = instance._meta
key = [opts.app_label, opts.model_name, instance.pk]
if label is not None:
key.append(label)
label = cache_key_func(key)
return cache_key(label=label, version=version, args=args, kwargs=kwargs)
示例12: init_spawn_value
def init_spawn_value(value, validator=None):
"""
Analyze the prototype value and produce a value useful at the point of spawning.
Args:
value (any): This can be:
callable - will be called as callable()
(callable, (args,)) - will be called as callable(*args)
other - will be assigned depending on the variable type
validator (callable, optional): If given, this will be called with the value to
check and guarantee the outcome is of a given type.
Returns:
any (any): The (potentially pre-processed value to use for this prototype key)
"""
value = protfunc_parser(value)
validator = validator if validator else lambda o: o
if callable(value):
return validator(value())
elif value and is_iter(value) and callable(value[0]):
# a structure (callable, (args, ))
args = value[1:]
return validator(value[0](*make_iter(args)))
else:
return validator(value)
示例13: handle_command
def handle_command(self, string):
"""
parse the commandstring and handle the command
the string is parsed into commands, and they are searched in the commandList-tree
the function returns an answerstring or that the command was ambigious
"""
# necessary since shlex does not support unicode prior to python 2.7.3
string = string.encode("utf-8")
s = shlex.split(string)
if not type(s) == list:
s=[s,]
if s[0] in self.commandList:
if callable(self.commandList[s[0]]):
return self._exec(self.commandList[s[0]], s[1:])
else:
return "Command \""+s[0]+"\" ambigious: "+", ".join(self.commandList[s[0]])
s.reverse()
cur=self.commandTree
while len(s) > 0:
n = s.pop()
if not n in cur:
return None
if callable(cur[n]):
s.reverse()
return self._exec(cur[n], s)
else:
cur=cur[n]
示例14: xop_request
def xop_request(ctx, request):
# TODO: add optional redirect-to-site?
if not ctx.can_access(request):
raise HTTPForbidden('Access Denied')
gw = ctx.get_gateway()
if (not gw) or (not hasattr(gw, 'process_request')):
raise HTTPForbidden('Access Denied')
if not callable(gw.process_request):
raise HTTPForbidden('Access Denied')
try:
sess = DBSession()
xoplist = gw.process_request(request, sess)
except Exception as e:
# TODO: cancel and log?
raise HTTPForbidden('Access Denied')
for xop in xoplist:
ctx.check_operation(xop)
sess.add(xop)
if hasattr(gw, 'generate_response') and callable(gw.generate_response):
return gw.generate_response(request, xoplist)
resp = Response(body='OK', content_type='text/plain', charset='UTF-8')
return resp
示例15: __init__
def __init__(self, verbose_name=None, accessor=None, default=None,
visible=True, orderable=None, attrs=None, order_by=None,
sortable=None, empty_values=None, localize=None):
if not (accessor is None or isinstance(accessor, six.string_types) or
callable(accessor)):
raise TypeError('accessor must be a string or callable, not %s' %
type(accessor).__name__)
if callable(accessor) and default is not None:
raise TypeError('accessor must be string when default is used, not callable')
self.accessor = A(accessor) if accessor else None
self._default = default
self.verbose_name = verbose_name
self.visible = visible
if sortable is not None:
warnings.warn('`sortable` is deprecated, use `orderable` instead.',
DeprecationWarning)
# if orderable hasn't been specified, we'll use sortable's value
if orderable is None:
orderable = sortable
self.orderable = orderable
self.attrs = attrs or {}
# massage order_by into an OrderByTuple or None
order_by = (order_by, ) if isinstance(order_by, six.string_types) else order_by
self.order_by = OrderByTuple(order_by) if order_by is not None else None
if empty_values is not None:
self.empty_values = empty_values
self.localize = localize
self.creation_counter = Column.creation_counter
Column.creation_counter += 1