本文整理匯總了Python中inspect.isfunction方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.isfunction方法的具體用法?Python inspect.isfunction怎麽用?Python inspect.isfunction使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.isfunction方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: describe_template_sets
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def describe_template_sets():
"""
Print the available template sets in this demo, with a short description"
"""
import inspect
import sys
# a bit of magic to get all functions in this module
templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
for (name, obj) in templatesets:
if name == "describe_template_sets":
continue
print(name, obj.__doc__, "\n")
######################################################################
# The Brill Tagger
######################################################################
示例2: get_matching_classes
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def get_matching_classes(self, loadable_class_names):
"""Get loadable classes from a list of names.
Each name can be a full module path or the full path to a
method that returns classes to use. The latter behavior
is useful to specify a method that returns a list of
classes to use in a default case.
"""
classes = []
for cls_name in loadable_class_names:
obj = importutils.import_class(cls_name)
if self._is_correct_class(obj):
classes.append(obj)
elif inspect.isfunction(obj):
# Get list of classes from a function
for cls in obj():
classes.append(cls)
else:
error_str = 'Not a class of the correct type'
raise exception.ClassNotFound(class_name=cls_name,
exception=error_str)
return classes
示例3: __new__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def __new__(cls, name, bases, attrs):
# A list of all functions which is marked as 'is_cronjob=True'
cron_jobs = []
# The min_tick is the greatest common divisor(GCD) of the interval of cronjobs
# this value would be queried by scheduler when the project initial loaded.
# Scheudler may only send _on_cronjob task every min_tick seconds. It can reduce
# the number of tasks sent from scheduler.
min_tick = 0
for each in attrs.values():
if inspect.isfunction(each) and getattr(each, 'is_cronjob', False):
cron_jobs.append(each)
min_tick = fractions.gcd(min_tick, each.tick)
newcls = type.__new__(cls, name, bases, attrs)
newcls._cron_jobs = cron_jobs
newcls._min_tick = min_tick
return newcls
示例4: validate
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def validate(self, value, data):
if self.condition is None and not self._is_empty(value):
need_validate = True
else:
assert isfunction(self.condition), \
'Condition should be a function for RequiresIf validator'
need_validate = self.condition(value, data)
if not need_validate:
return True
fields = []
for field in self.fields:
val = data.get(field)
if val is None or val == '':
fields.append(field)
if fields:
self.put_msg(
'For given input, fields are required: %s' % ', '.join(fields)
)
return False
return True
示例5: _get_name_of_callable
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def _get_name_of_callable(cls, c):
if inspect.ismethod(c):
return c.im_class.__name__+'.'+c.__name__
if inspect.isfunction(c):
if c.__name__ == (lambda: None).__name__:
filename = c.func_code.co_filename
cls._ensure_file_in_cache(filename, c)
definitions = cls._LAMBDA_CACHE[filename][c.func_code.co_firstlineno]
assert definitions
# If there's multiple definitions at the same line, there's not enough
# information to distinguish which lambda c refers to, so just let
# python's generic lambda name be used
if len(definitions) == 1:
return astunparse.unparse(definitions[0]).strip()
return c.__name__
if hasattr(c, '__call__'):
return c.__class__.__name__+'.__call__'
return repr(c)
示例6: register_check
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def register_check(check, codes=None):
"""Register a new check object."""
def _add_check(check, kind, codes, args):
if check in _checks[kind]:
_checks[kind][check][0].extend(codes or [])
else:
_checks[kind][check] = (codes or [''], args)
if inspect.isfunction(check):
args = _get_parameters(check)
if args and args[0] in ('physical_line', 'logical_line'):
if codes is None:
codes = ERRORCODE_REGEX.findall(check.__doc__ or '')
_add_check(check, args[0], codes, args)
elif inspect.isclass(check):
if _get_parameters(check.__init__)[:2] == ['self', 'tree']:
_add_check(check, 'tree', codes, None)
return check
##############################################################################
# Plugins (check functions) for physical lines
##############################################################################
示例7: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def __init__(self, *args, **kwargs):
self.pan_device = kwargs.pop('pan_device', None)
pan.xapi.PanXapi.__init__(self, *args, **kwargs)
pred = lambda x: inspect.ismethod(x) or inspect.isfunction(x) # inspect.ismethod needed for Python2, inspect.isfunction needed for Python3
for name, method in inspect.getmembers(
pan.xapi.PanXapi,
pred):
# Ignore hidden methods
if name[0] == "_":
continue
# Ignore non-api methods
if name in ('xml_result', 'xml_root', 'cmd_xml'):
continue
# Wrapper method. This is used to create
# methods in this class that match the methods in the
# super class, and call the super class methods inside
# a try/except block, which allows us to check and
# analyze the exceptions and convert them to more
# useful exceptions than generic PanXapiErrors.
wrapper_method = PanDevice.XapiWrapper.make_method(name, method)
# Create method matching each public method of the base class
setattr(PanDevice.XapiWrapper, name, wrapper_method)
示例8: try_serialize_handler
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def try_serialize_handler(handler):
"""Try to serialize map/reduce handler.
Args:
handler: handler function/instance. Handler can be a function or an
instance of a callable class. In the latter case, the handler will
be serialized across slices to allow users to save states.
Returns:
serialized handler string or None.
"""
if (isinstance(handler, types.InstanceType) or # old style class
(isinstance(handler, object) and # new style class
not inspect.isfunction(handler) and
not inspect.ismethod(handler)) and
hasattr(handler, "__call__")):
return pickle.dumps(handler)
return None
示例9: is_generator
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def is_generator(obj):
"""Return true if the object is generator or generator function.
Generator function objects provides same attributes as functions.
See isfunction.__doc__ for attributes listing.
Adapted from Python 2.6.
Args:
obj: an object to test.
Returns:
true if the object is generator function.
"""
if isinstance(obj, types.GeneratorType):
return True
CO_GENERATOR = 0x20
return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and
obj.func_code.co_flags & CO_GENERATOR))
示例10: is_generator_function
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def is_generator_function(obj):
"""Return true if the object is a user-defined generator function.
Generator function objects provides same attributes as functions.
See isfunction.__doc__ for attributes listing.
Adapted from Python 2.6.
Args:
obj: an object to test.
Returns:
true if the object is generator function.
"""
CO_GENERATOR = 0x20
return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and
obj.func_code.co_flags & CO_GENERATOR))
示例11: applicationpolicy
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def applicationpolicy(arg: Callable) -> Callable:
"""
Decorator for application policy method.
Allows policy to be built up from methods
registered for different event classes.
"""
assert isfunction(arg), arg
@no_type_check
def _mutator(func):
wrapped = singledispatch(func)
@wraps(wrapped)
def wrapper(*args, **kwargs):
event = kwargs.get("event") or args[-1]
return wrapped.dispatch(type(event))(*args, **kwargs)
wrapper.register = wrapped.register
return wrapper
return _mutator(arg)
示例12: encoderpolicy
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def encoderpolicy(arg=None):
"""
Decorator for encoder policy.
Allows default behaviour to be built up from methods
registered for different types of things, rather than
chain of isinstance() calls in a long if-else block.
"""
def _mutator(func):
wrapped = singledispatch(func)
@wraps(wrapped)
def wrapper(*args, **kwargs):
obj = kwargs.get("obj") or args[-1]
return wrapped.dispatch(type(obj))(*args, **kwargs)
wrapper.register = wrapped.register
return wrapper
assert isfunction(arg), arg
return _mutator(arg)
示例13: attribute
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def attribute(getter: Callable) -> property:
"""
When used as a method decorator, returns a property object
with the method as the getter and a setter defined to call
instance method __change_attribute__(), which publishes an
AttributeChanged event.
"""
if isfunction(getter):
@no_type_check
def setter(self, value):
name = "_" + getter.__name__
self.__change_attribute__(name=name, value=value)
@no_type_check
def new_getter(self):
name = "_" + getter.__name__
return getattr(self, name, None)
return property(fget=new_getter, fset=setter, doc=getter.__doc__)
else:
raise ProgrammingError("Expected a function, got: {}".format(repr(getter)))
示例14: decorator
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def decorator(target):
"""A signature-matching decorator factory."""
def decorate(fn):
if not inspect.isfunction(fn):
raise Exception("not a decoratable function")
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)
metadata.update(format_argspec_plus(spec, grouped=False))
metadata['name'] = fn.__name__
code = """\
def %(name)s(%(args)s):
return %(target)s(%(fn)s, %(apply_kw)s)
""" % metadata
decorated = _exec_code_in_env(code,
{targ_name: target, fn_name: fn},
fn.__name__)
decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
decorated.__wrapped__ = fn
return update_wrapper(decorated, fn)
return update_wrapper(decorate, target)
示例15: check_all_contracts
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isfunction [as 別名]
def check_all_contracts(*args, decorate_main=True) -> None:
"""Automatically check contracts for all functions and classes in the given module.
When called with no arguments, the current module's functions and classes are checked.
"""
modules = []
if decorate_main:
modules.append(sys.modules["__main__"])
for module_name in args:
modules.append(sys.modules.get(module_name, None))
for module in modules:
if not module:
# Module name was passed in incorrectly.
continue
for name, value in inspect.getmembers(module):
if inspect.isfunction(value):
module.__dict__[name] = check_contracts(value)
elif inspect.isclass(value):
add_class_invariants(value)