def add(self, categorize):
"""Add given method to categorize messages. When a message is received,
each of the added methods (most recently added method first) is called
with the message. The method should return a category (any hashable
object) or None (in which case next recently added method is called with
the same message). If all the methods return None for a given message,
the message is queued with category=None, so that 'receive' method here
works just as Task.receive.
"""
if inspect.isfunction(categorize):
argspec = inspect.getargspec(categorize)
if len(argspec.args) != 1:
categorize = None
elif type(categorize) != partial_func:
categorize = None
if categorize:
self._categorize.insert(0, categorize)
else:
logger.warning('invalid categorize function ignored')
python类isfunction()的实例源码
def add(self, categorize):
"""Add given method to categorize messages. When a message is received,
each of the added methods (most recently added method first) is called
with the message. The method should return a category (any hashable
object) or None (in which case next recently added method is called with
the same message). If all the methods return None for a given message,
the message is queued with category=None, so that 'receive' method here
works just as Task.receive.
"""
if inspect.isfunction(categorize):
argspec = inspect.getargspec(categorize)
if len(argspec.args) != 1:
categorize = None
elif type(categorize) != partial_func:
categorize = None
if categorize:
self._categorize.insert(0, categorize)
else:
logger.warning('invalid categorize function ignored')
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def inject(*args):
if len(args) == 1 and inspect.isfunction(args[0]):
return inject_function(args[0])
else:
def inject_class(cls):
orig_init = cls.__init__
def __init__(self, *a, **kw):
container = Container()
for arg in args:
obj = container.get_object(arg)
setattr(self, arg, obj)
orig_init(self, *a, **kw)
cls.__init__ = __init__
return cls
return inject_class
def addWidget(self, w, name=None, scale=None):
if not self.acceptsType(w):
raise Exception("Widget type %s not supported by WidgetGroup" % type(w))
if name is None:
name = str(w.objectName())
if name == '':
raise Exception("Cannot add widget '%s' without a name." % str(w))
self.widgetList[w] = name
self.scales[w] = scale
self.readWidget(w)
if type(w) in WidgetGroup.classes:
signal = WidgetGroup.classes[type(w)][0]
else:
signal = w.widgetGroupInterface()[0]
if signal is not None:
if inspect.isfunction(signal) or inspect.ismethod(signal):
signal = signal(w)
signal.connect(self.mkChangeCallback(w))
else:
self.uncachedWidgets[w] = None
def addWidget(self, w, name=None, scale=None):
if not self.acceptsType(w):
raise Exception("Widget type %s not supported by WidgetGroup" % type(w))
if name is None:
name = str(w.objectName())
if name == '':
raise Exception("Cannot add widget '%s' without a name." % str(w))
self.widgetList[w] = name
self.scales[w] = scale
self.readWidget(w)
if type(w) in WidgetGroup.classes:
signal = WidgetGroup.classes[type(w)][0]
else:
signal = w.widgetGroupInterface()[0]
if signal is not None:
if inspect.isfunction(signal) or inspect.ismethod(signal):
signal = signal(w)
signal.connect(self.mkChangeCallback(w))
else:
self.uncachedWidgets[w] = None
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)
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.isfunction(object):
return module.__dict__ is func_globals(object)
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def describe(module):
""" Describe the module object passed as argument
including its classes and functions """
wi('[Module: %s]\n' % module.__name__)
indent()
count = 0
for name in dir(module):
obj = getattr(module, name)
if inspect.isclass(obj):
count += 1; describe_klass(obj)
elif (inspect.ismethod(obj) or inspect.isfunction(obj)):
count +=1 ; describe_func(obj)
elif inspect.isbuiltin(obj):
count += 1; describe_builtin(obj)
if count==0:
wi('(No members)')
dedent()
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)
def activation_str(self):
"""
Get printable string from activation function.
:return: string
"""
if hasattr(self, 'activation'):
if self.activation is None:
return str(None)
elif inspect.isclass(self.activation):
return self.activation.__class__.__name__
elif inspect.isfunction(self.activation):
return self.activation.__name__
else:
return str(self.activation)
else:
return ''
def add_handlers(self, namespace):
"""
Add handler functions from the given `namespace`, for instance a module.
The namespace may be a string, in which case it is expected to be a name of a module.
It may also be a dictionary mapping names to functions.
Only non-underscore-prefixed functions and methods are imported.
:param namespace: Namespace object.
:type namespace: str|module|dict[str, function]
"""
if isinstance(namespace, str):
namespace = import_module(namespace)
if isinstance(namespace, dict):
namespace = namespace.items()
else:
namespace = vars(namespace).items()
for name, value in namespace:
if name.startswith('_'):
continue
if isfunction(value) or ismethod(value):
self.handlers[name] = value
def add_network_methods(target):
'''
Attach extension methods to an object that represents a Veneer network.
Note: The 'network_' prefix will be removed from method names.
target: Veneer network object to attach extension methods to.
'''
import veneer.extensions as extensions # Import self to inspect available functions
# Generate dict of {function name: function}, skipping this function
this_func_name = sys._getframe().f_code.co_name
funcs = inspect.getmembers(extensions, inspect.isfunction)
funcs = dict((func_name, func) for func_name, func in funcs
if func_name != this_func_name
)
# Assign functions to target, removing the 'network_' prefix
for f_name, f in funcs.items():
if f_name.startswith('network_'):
f_name = f_name.replace('network_', '')
setattr(target, f_name, MethodType(f, target))
def _get_queryset_methods(cls, queryset_class):
def create_method(name, method):
def manager_method(self, *args, **kwargs):
return getattr(self.get_queryset(), name)(*args, **kwargs)
manager_method.__name__ = method.__name__
manager_method.__doc__ = method.__doc__
return manager_method
new_methods = {}
# Refs http://bugs.python.org/issue1785.
predicate = inspect.isfunction if six.PY3 else inspect.ismethod
for name, method in inspect.getmembers(queryset_class, predicate=predicate):
# Only copy missing methods.
if hasattr(cls, name):
continue
# Only copy public methods or methods with the attribute `queryset_only=False`.
queryset_only = getattr(method, 'queryset_only', None)
if queryset_only or (queryset_only is None and name.startswith('_')):
continue
# Copy the method onto the manager.
new_methods[name] = create_method(name, method)
return new_methods
def __new__(cls, name, bases, attrs):
get_form = attrs.get('get_form')
if get_form and inspect.isfunction(get_form):
try:
inspect.getcallargs(get_form, None)
except TypeError:
warnings.warn(
"`%s.%s.get_form` method must define a default value for "
"its `form_class` argument." % (attrs['__module__'], name),
RemovedInDjango110Warning, stacklevel=2
)
def get_form_with_form_class(self, form_class=None):
if form_class is None:
form_class = self.get_form_class()
return get_form(self, form_class=form_class)
attrs['get_form'] = get_form_with_form_class
return super(FormMixinBase, cls).__new__(cls, name, bases, attrs)
def __init__(self, Class):
self.uniforms = []
self.program = None
self.error = 0
for key, value in Class.__dict__.items() :
if key.startswith('__'): continue
if inspect.ismethod(getattr(Class, key)): continue
if inspect.isfunction(getattr(Class, key)): continue
self.__dict__[key] = value
self.uniforms.append(key)
if not self.owner:
from bge import logic
self.owner = logic.getCurrentController().owner
self.uniforms = [x for x in self.uniforms if x not in self.owner.getPropertyNames()]
def getAttrFromPython(path, classname):
with open(path) as f: code = f.read()
code = code.replace('import filter2D', '#')
code = code.replace('from filter2D', '#')
code = "class Filter2D: pass\n" + code
code = compile(code, path, 'exec')
myglob = dict()
exec(code, dict(), myglob)
attr = dict()
_class = myglob[classname]
for key, value in _class.__dict__.items():
if key.startswith('__'): continue
if inspect.ismethod(getattr(_class, key)): continue
if inspect.isfunction(getattr(_class, key)): continue
attr[key]=value
return attr
def getTestCaseNames(self, testCaseClass):
"""Override to select with selector, unless
config.getTestCaseNamesCompat is True
"""
if self.config.getTestCaseNamesCompat:
return unittest.TestLoader.getTestCaseNames(self, testCaseClass)
def wanted(attr, cls=testCaseClass, sel=self.selector):
item = getattr(cls, attr, None)
if isfunction(item):
item = unbound_method(cls, item)
elif not ismethod(item):
return False
return sel.wantMethod(item)
cases = filter(wanted, dir(testCaseClass))
# add runTest if nothing else picked
if not cases and hasattr(testCaseClass, 'runTest'):
cases = ['runTest']
if self.sortTestMethodsUsing:
sort_list(cases, cmp_to_key(self.sortTestMethodsUsing))
return cases
def loadTestsFromTestClass(self, cls):
"""Load tests from a test class that is *not* a unittest.TestCase
subclass.
In this case, we can't depend on the class's `__init__` taking method
name arguments, so we have to compose a MethodTestCase for each
method in the class that looks testlike.
"""
def wanted(attr, cls=cls, sel=self.selector):
item = getattr(cls, attr, None)
if isfunction(item):
item = unbound_method(cls, item)
elif not ismethod(item):
return False
return sel.wantMethod(item)
cases = [self.makeTest(getattr(cls, case), cls)
for case in filter(wanted, dir(cls))]
for test in self.config.plugins.loadTestsFromTestClass(cls):
cases.append(test)
return self.suiteClass(ContextList(cases, context=cls))
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
# Some jython classes don't set __module__
return module.__name__ == getattr(object, '__module__', None)
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def add_handlers(self, namespace):
"""
Add handler functions from the given `namespace`, for instance a module.
The namespace may be a string, in which case it is expected to be a name of a module.
It may also be a dictionary mapping names to functions.
Only non-underscore-prefixed functions and methods are imported.
:param namespace: Namespace object.
:type namespace: str|module|dict[str, function]
"""
if isinstance(namespace, str):
namespace = import_module(namespace)
if isinstance(namespace, dict):
namespace = namespace.items()
else:
namespace = vars(namespace).items()
for name, value in namespace:
if name.startswith('_'):
continue
if isfunction(value) or ismethod(value):
self.handlers[name] = value
def get_defining_item(self, code):
for modname, mod in sys.modules.iteritems():
file = getattr(mod, '__file__', '').replace('.pyc', '.py')
if file == code.co_filename:
for classname,clazz in inspect.getmembers(mod, predicate=inspect.isclass):
for name,member in inspect.getmembers(clazz, predicate=inspect.ismethod):
filename = member.im_func.func_code.co_filename
lineno = member.im_func.func_code.co_firstlineno
if filename == code.co_filename and lineno == code.co_firstlineno:
self.imports_.add((modname, clazz.__name__))
return clazz, member
for name,member in inspect.getmembers(clazz, predicate=inspect.isfunction):
filename = member.func_code.co_filename
lineno = member.func_code.co_firstlineno
if filename == code.co_filename and lineno == code.co_firstlineno:
self.imports_.add((modname, clazz.__name__))
return clazz, member
self.imports_.add((modname,))
return mod, mod
def _get_function_source(func):
if _PY34:
func = inspect.unwrap(func)
elif hasattr(func, '__wrapped__'):
func = func.__wrapped__
if inspect.isfunction(func):
code = func.__code__
return (code.co_filename, code.co_firstlineno)
if isinstance(func, functools.partial):
return _get_function_source(func.func)
if _PY34 and isinstance(func, functools.partialmethod):
return _get_function_source(func.func)
return None
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)
def get_cache_key(self, *args, **kwargs):
callargs = inspect.getcallargs(self.fn, *args, **kwargs)
values = []
if isfunction(self.vary_on):
values = self.vary_on(*args, **kwargs)
else:
for arg_name, attrs in self.vary_on:
value = callargs[arg_name]
for attr in attrs:
value = getattr(value, attr)
values.append(value)
args_string = ','.join(self._serialize_for_key(value)
for value in values)
if len(args_string) > 150:
args_string = 'H' + self._hash(args_string)
return 'quickcache.{}/{}'.format(self.prefix, args_string)
def get_callable_name(function):
"""Generate a name from callable.
Tries to do the best to guess fully qualified callable name.
"""
method_self = get_method_self(function)
if method_self is not None:
# This is a bound method.
if isinstance(method_self, six.class_types):
# This is a bound class method.
im_class = method_self
else:
im_class = type(method_self)
try:
parts = (im_class.__module__, function.__qualname__)
except AttributeError:
parts = (im_class.__module__, im_class.__name__, function.__name__)
elif inspect.ismethod(function) or inspect.isfunction(function):
# This could be a function, a static method, a unbound method...
try:
parts = (function.__module__, function.__qualname__)
except AttributeError:
if hasattr(function, 'im_class'):
# This is a unbound method, which exists only in python 2.x
im_class = function.im_class
parts = (im_class.__module__,
im_class.__name__, function.__name__)
else:
parts = (function.__module__, function.__name__)
else:
im_class = type(function)
if im_class is _TYPE_TYPE:
im_class = function
try:
parts = (im_class.__module__, im_class.__qualname__)
except AttributeError:
parts = (im_class.__module__, im_class.__name__)
return '.'.join(parts)
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
python_filter_generator.py 文件源码
项目:ParaViewGeophysics
作者: banesullivan
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def replaceFunctionWithSourceString(namespace, functionName, allowEmpty=False):
func = namespace.get(functionName)
if not func:
if allowEmpty:
namespace[functionName] = ''
return
else:
raise Exception('Function %s not found in input source code.' % functionName)
if not inspect.isfunction(func):
raise Exception('Object %s is not a function object.' % functionName)
lines = inspect.getsourcelines(func)[0]
if len(lines) <= 1:
raise Exception('Function %s must not be a single line of code.' % functionName)
# skip first line (the declaration) and then dedent the source code
sourceCode = textwrap.dedent(''.join(lines[1:]))
namespace[functionName] = sourceCode
def decorate_func_or_method_or_class(decorator):
"""Applies a decorator to a function, method, or all methods of a class.
This is a decorator that is applied to a decorator to allow a
function/method decorator to be applied to a class and have it act on all
test methods of the class.
"""
def decorate(func_or_class):
if inspect.isclass(func_or_class):
return decorate_all_test_methods(decorator)(func_or_class)
elif inspect.isfunction(func_or_class):
return decorator(func_or_class)
else:
assert False, 'Target of decorator must be function or class'
return decorate