def get_containing_module(value):
"""
Return the name of the module containing the given value, or
C{None} if the module name can't be determined.
@rtype: L{DottedName}
"""
if inspect.ismodule(value):
return DottedName(value.__name__)
elif isclass(value):
return DottedName(value.__module__)
elif (inspect.ismethod(value) and value.im_self is not None and
value.im_class is ClassType): # class method.
return DottedName(value.im_self.__module__)
elif inspect.ismethod(value):
return DottedName(value.im_class.__module__)
elif inspect.isroutine(value):
module = _find_function_module(value)
if module is None: return None
return DottedName(module)
else:
return None
python类ismethod()的实例源码
def boundmethod(func, callback=None):
"""
Return a weakly-bound instance method from the given bound method. If
callback is provided and not None, the callback will be called when the
referenced object (the method's self) is about to be finalized; the weakly-
bound instance method will be passed to the callback.
If func is already a weakly-bound instance method, return a new weakly-
bound instance method to the underlying bound method.
"""
if inspect.ismethod(func):
return WeakBoundMethod(func, callback)
elif isinstance(func, bound_notification):
return WeakNotification(func, callback)
elif isinstance(func, _WeakCallable):
return boundmethod(getref(func), callback)
else:
raise TypeError("can not create weakly-bound method from '%s' object" % (type(func).__name__,))
def uses_tags(self):
members = inspect.getmembers(self, predicate=inspect.ismethod)
handles = [member for member in members if member[0].startswith("handle_") or member[0] == 'preprocess']
alltags = set([])
for handle in handles:
if handle[0].startswith("handle_"):
alltags.add(handle[0][len("handle_"):])
doc = handle[1].__doc__
if not doc:
continue
for line in doc.splitlines():
m = re.search(r"Uses tags:(.+)", line)
if m:
tags = m.group(1).split(",")
tags = [tag.strip() for tag in tags]
alltags.update(tags)
alltags.update(self.enumerateable_envs.keys())
return alltags
def uses_tags(self) -> set:
members = inspect.getmembers(self, predicate=inspect.ismethod)
handles = [member for member in members
if (member[0].startswith("handle_") or
member[0] == 'make_numbers')]
alltags = set([])
for handle in handles:
if handle[0].startswith("handle_"):
alltags.add(handle[0][len("handle_"):])
doc = handle[1].__doc__
if not doc:
continue
for line in doc.splitlines():
m = re.search(r"Uses tags:(.+)", line)
if m:
tags = m.group(1).split(",")
tags = [tag.strip() for tag in tags]
alltags.update(tags)
alltags.update(self.enumerateable_envs.keys())
alltags.update(self.metatags)
return alltags
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 readWidget(self, w):
if type(w) in WidgetGroup.classes:
getFunc = WidgetGroup.classes[type(w)][1]
else:
getFunc = w.widgetGroupInterface()[1]
if getFunc is None:
return None
## if the getter function provided in the interface is a bound method,
## then just call the method directly. Otherwise, pass in the widget as the first arg
## to the function.
if inspect.ismethod(getFunc) and getFunc.__self__ is not None:
val = getFunc()
else:
val = getFunc(w)
if self.scales[w] is not None:
val /= self.scales[w]
#if isinstance(val, QtCore.QString):
#val = str(val)
n = self.widgetList[w]
self.cache[n] = val
return val
def setWidget(self, w, v):
v1 = v
if self.scales[w] is not None:
v *= self.scales[w]
if type(w) in WidgetGroup.classes:
setFunc = WidgetGroup.classes[type(w)][2]
else:
setFunc = w.widgetGroupInterface()[2]
## if the setter function provided in the interface is a bound method,
## then just call the method directly. Otherwise, pass in the widget as the first arg
## to the function.
if inspect.ismethod(setFunc) and setFunc.__self__ is not None:
setFunc(v)
else:
setFunc(w, v)
#name = self.widgetList[w]
#if name in self.cache and (self.cache[name] != v1):
#print "%s: Cached value %s != set value %s" % (name, str(self.cache[name]), str(v1))
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 readWidget(self, w):
if type(w) in WidgetGroup.classes:
getFunc = WidgetGroup.classes[type(w)][1]
else:
getFunc = w.widgetGroupInterface()[1]
if getFunc is None:
return None
## if the getter function provided in the interface is a bound method,
## then just call the method directly. Otherwise, pass in the widget as the first arg
## to the function.
if inspect.ismethod(getFunc) and getFunc.__self__ is not None:
val = getFunc()
else:
val = getFunc(w)
if self.scales[w] is not None:
val /= self.scales[w]
#if isinstance(val, QtCore.QString):
#val = str(val)
n = self.widgetList[w]
self.cache[n] = val
return val
def describe_klass(obj):
""" Describe the class object passed as argument,
including its methods """
wi('+Class: %s' % obj.__name__)
indent()
count = 0
for name in obj.__dict__:
item = getattr(obj, name)
if inspect.ismethod(item):
count += 1;describe_func(item, True)
if count==0:
wi('(No members)')
dedent()
print
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 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 check_all_models(app_configs=None, **kwargs):
errors = []
for model in apps.get_models():
if app_configs is None or model._meta.app_config in app_configs:
if not inspect.ismethod(model.check):
errors.append(
Error(
"The '%s.check()' class method is "
"currently overridden by %r." % (
model.__name__, model.check),
hint=None,
obj=model,
id='models.E020'
)
)
else:
errors.extend(model.check(**kwargs))
return errors
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 __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 check_all_models(app_configs=None, **kwargs):
errors = []
if app_configs is None:
models = apps.get_models()
else:
models = chain.from_iterable(app_config.get_models() for app_config in app_configs)
for model in models:
if not inspect.ismethod(model.check):
errors.append(
Error(
"The '%s.check()' class method is currently overridden by %r."
% (model.__name__, model.check),
obj=model,
id='models.E020'
)
)
else:
errors.extend(model.check(**kwargs))
return errors
def _get_xunit_setup_teardown(holder, attr_name, param_obj=None):
"""
Return a callable to perform xunit-style setup or teardown if
the function exists in the ``holder`` object.
The ``param_obj`` parameter is the parameter which will be passed to the function
when the callable is called without arguments, defaults to the ``holder`` object.
Return ``None`` if a suitable callable is not found.
"""
param_obj = param_obj if param_obj is not None else holder
result = _get_xunit_func(holder, attr_name)
if result is not None:
arg_count = result.__code__.co_argcount
if inspect.ismethod(result):
arg_count -= 1
if arg_count:
return lambda: result(param_obj)
else:
return result
def setup(self):
""" perform setup for this test function. """
if hasattr(self, '_preservedparent'):
obj = self._preservedparent
elif isinstance(self.parent, Instance):
obj = self.parent.newinstance()
self.obj = self._getobj()
else:
obj = self.parent.obj
if inspect.ismethod(self.obj):
setup_name = 'setup_method'
teardown_name = 'teardown_method'
else:
setup_name = 'setup_function'
teardown_name = 'teardown_function'
setup_func_or_method = _get_xunit_setup_teardown(obj, setup_name, param_obj=self.obj)
if setup_func_or_method is not None:
setup_func_or_method()
teardown_func_or_method = _get_xunit_setup_teardown(obj, teardown_name, param_obj=self.obj)
if teardown_func_or_method is not None:
self.addfinalizer(teardown_func_or_method)
def _get_all(self):
#If this is a MOR we need to recurse
if self._type == 'ManagedObjectReference':
oc = self._server._get_object_properties(self._obj, get_all=True)
ps = oc.get_element_propSet()
self._values = dict([(i.Name, i.Val) for i in ps])
#Just inspect the attributes
else:
methods = getmembers(self._obj, predicate=inspect.ismethod)
self._values = {}
for name, method in methods:
try:
if name.startswith("get_element_"):
self._values[name[12:]] = method()
except AttributeError:
continue
self._values_set = True
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 __init__(self, docstring, class_name, class_object):
super(NumpyClassDocString, self).__init__(docstring)
self.class_name = class_name
methods = dict((name, func) for name, func
in inspect.getmembers(class_object))
self.has_parameters = False
if '__init__' in methods:
# verify if __init__ is a Python function. If it isn't
# (e.g. the function is implemented in C), getargspec will fail
if not inspect.ismethod(methods['__init__']):
return
args, varargs, keywords, defaults = inspect.getargspec(
methods['__init__'])
if (args and args != ['self']) or varargs or keywords or defaults:
self.has_parameters = True
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 check_all_models(app_configs=None, **kwargs):
errors = []
if app_configs is None:
models = apps.get_models()
else:
models = chain.from_iterable(app_config.get_models() for app_config in app_configs)
for model in models:
if not inspect.ismethod(model.check):
errors.append(
Error(
"The '%s.check()' class method is currently overridden by %r."
% (model.__name__, model.check),
obj=model,
id='models.E020'
)
)
else:
errors.extend(model.check(**kwargs))
return errors
def get_all_parameters(cls, parsed_args):
prefix = _get_prefix(cls)
if prefix is None or len(prefix) == 0:
raise ValueError('Cannot retrieve parameters without prefix')
info = _get_info(cls)
if inspect.ismethod(cls.__init__):
spec = inspect.getargspec(cls.__init__)
if spec.defaults is None:
arg_defaults = {}
else:
arg_defaults = dict(list(zip(spec.args[::-1], spec.defaults[::-1])))
else:
arg_defaults = {}
all_params = {}
for arg_name, arg_info in info.items():
prefixed_name = prefix + arg_name
arg_value = None
if hasattr(parsed_args, prefixed_name):
arg_value = getattr(parsed_args, prefixed_name)
if arg_value is None and arg_name in arg_defaults:
arg_value = arg_defaults[arg_name]
if arg_value is not None:
all_params[arg_name] = arg_value
return all_params
def getargspec(func):
"""Variation of inspect.getargspec that works for more functions.
This function works for Cythonized, non-cpdef functions, which expose argspec information but
are not accepted by getargspec. It also works for Python 3 functions that use annotations, which
are simply ignored. However, keyword-only arguments are not supported.
"""
if inspect.ismethod(func):
func = func.__func__
# Cythonized functions have a .__code__, but don't pass inspect.isfunction()
try:
code = func.__code__
except AttributeError:
raise TypeError('{!r} is not a Python function'.format(func))
if hasattr(code, 'co_kwonlyargcount') and code.co_kwonlyargcount > 0:
raise ValueError('keyword-only arguments are not supported by getargspec()')
args, varargs, varkw = inspect.getargs(code)
return inspect.ArgSpec(args, varargs, varkw, func.__defaults__)
def get_instance_public_methods(instance):
"""Retrieves an objects public methods
:param instance: The instance of the class to inspect
:rtype: dict
:returns: A dictionary that represents an instance's methods where
the keys are the name of the methods and the
values are the handler to the method.
"""
instance_members = inspect.getmembers(instance)
instance_methods = {}
for name, member in instance_members:
if not name.startswith('_'):
if inspect.ismethod(member):
instance_methods[name] = member
return instance_methods
def check_all_models(app_configs=None, **kwargs):
errors = []
if app_configs is None:
models = apps.get_models()
else:
models = chain.from_iterable(app_config.get_models() for app_config in app_configs)
for model in models:
if not inspect.ismethod(model.check):
errors.append(
Error(
"The '%s.check()' class method is currently overridden by %r."
% (model.__name__, model.check),
obj=model,
id='models.E020'
)
)
else:
errors.extend(model.check(**kwargs))
return errors
def _get_argspec(func):
"""Returns an inspect.ArgSpec instance given a function object.
We prefer this implementation rather than the inspect module's getargspec
since the latter has a strict check that the passed function is an instance
of FunctionType. Cython functions do not pass this check, but they do implement
the `func_code` and `func_defaults` attributes that we need to produce an Argspec.
This implementation re-uses much of inspect.getargspec but removes the strict
check allowing interface failures to be raised as AttributeError.
See Also:
https://github.com/python/cpython/blob/2.7/Lib/inspect.py
"""
if inspect.ismethod(func):
func = func.im_func
args, varargs, varkw = inspect.getargs(func.func_code)
return inspect.ArgSpec(args, varargs, varkw, func.func_defaults)