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
python类ismethod()的实例源码
def __Insert(self, index, key, function, service=None):
"""Appends a hook at a certain position in the list.
Args:
index: the index of where to insert the function
key: a unique key (within the module) for this particular function.
If something from the same module with the same key is already
registered, nothing will be added.
function: the hook to be added.
service: optional argument that restricts the hook to a particular api
Returns:
True if the collection was modified.
"""
unique_key = (key, inspect.getmodule(function))
if unique_key in self.__unique_keys:
return False
num_args = len(inspect.getargspec(function)[0])
if (inspect.ismethod(function)):
num_args -= 1
self.__content.insert(index, (key, function, service, num_args))
self.__unique_keys.add(unique_key)
return True
def __Insert(self, index, key, function, service=None):
"""Appends a hook at a certain position in the list.
Args:
index: the index of where to insert the function
key: a unique key (within the module) for this particular function.
If something from the same module with the same key is already
registered, nothing will be added.
function: the hook to be added.
service: optional argument that restricts the hook to a particular api
Returns:
True if the collection was modified.
"""
unique_key = (key, inspect.getmodule(function))
if unique_key in self.__unique_keys:
return False
num_args = len(inspect.getargspec(function)[0])
if (inspect.ismethod(function)):
num_args -= 1
self.__content.insert(index, (key, function, service, num_args))
self.__unique_keys.add(unique_key)
return True
def get_category(attr):
if inspect.isclass(attr):
return EXCEPTION if issubclass(attr, Exception) else CLASS
elif inspect.isfunction(attr):
return FUNCTION
elif inspect.ismethod(attr):
return FUNCTION
elif inspect.isbuiltin(attr):
return FUNCTION
elif isinstance(attr, method_descriptor):
# Technically, method_descriptor is descriptor, but since they
# act as functions, let's treat them as functions.
return FUNCTION
elif is_descriptor(attr):
# Maybe add getsetdescriptor memberdescriptor in the future.
return DESCRIPTOR
else:
return DEFAULT_CATEGORY
def copy(self):
""" Create a dopy of this simpype.Message object.
Returns:
:class:`Message`
"""
message = Message(self.sim, self.generator, self.id)
message.generated = copy.deepcopy(self.generated)
message.resource = self.resource
message.location = self.location
message.seq_num = copy.deepcopy(self.seq_num)
message.visited = copy.copy(self.visited)
message.is_alive = copy.deepcopy(self.is_alive)
message.next = copy.copy(self.next)
message.pipeline = copy.copy(self.pipeline)
for p in self.property.values():
message.property[p.name] = p.copy()
for id,s in self.subscription.items():
c = getattr(message, s.callback.__name__) if inspect.ismethod(s.callback) else s.callback
s = message.subscribe(event = s.event, callback = c, id = id)
return message
def default(self, obj):
if hasattr(obj, "to_json"):
return self.default(obj.to_json())
elif hasattr(obj, "__dict__"):
d = dict(
(key, value)
for key, value in inspect.getmembers(obj)
if not key.startswith("__")
and not inspect.isabstract(value)
and not inspect.isbuiltin(value)
and not inspect.isfunction(value)
and not inspect.isgenerator(value)
and not inspect.isgeneratorfunction(value)
and not inspect.ismethod(value)
and not inspect.ismethoddescriptor(value)
and not inspect.isroutine(value)
)
return self.default(d)
return obj
def __init__(self):
self.pub_commands = {}
self.worker_thread = None
members = inspect.getmembers(self, predicate=inspect.ismethod)
# print(members)
for (func_name, func_handler) in members:
if hasattr(func_handler, '__remote_yowsup__'):
self.pub_commands[func_name] = {
"fn": func_handler,
"args": inspect.getargspec(func_handler)[0][1:]
}
print(self.pub_commands[func_name])
self.worker_thread = ZmqServer(self.pub_commands)
def _wrap(self, i):
if not inspect.ismethod(i):
return i
# create a wrapper function
# that hijacks any ColumnValueMixins
def _wrapper(*args, **kwargs):
result = i(*args, **kwargs)
if not isinstance(result, md_operators.ColumnValueMixin):
return result
result.column = self
return result
return _wrapper
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 get_signature(obj, method_name):
method = getattr(obj, method_name)
# Eat self for unbound methods bc signature doesn't do it
if PY3:
if (inspect.isclass(obj) and
not inspect.ismethod(method) and
not isinstance(
obj.__dict__.get(method_name),
staticmethod)):
method = functools.partial(method, None)
else:
if (isinstance(method, types.UnboundMethodType) and
method.__self__ is None):
method = functools.partial(method, None)
try:
return signature(method)
except:
return None
def __new__(cls, name, bases, attrs):
super_new = super(AccountActionMetaclass, cls).__new__
parents = [base for base in bases if isinstance(base, AccountActionMetaclass)]
if not parents:
# We stop here if we are considering AccountActionBase and not
# one of its subclasses
return super_new(cls, name, bases, attrs)
new_action = super_new(cls, name, bases, attrs)
# Performs some checks
action_name = getattr(new_action, 'name', None)
if action_name is None or not isinstance(action_name, six.string_types):
raise ImproperlyConfigured('The "name" attribute must be a string')
execute_method = getattr(new_action, 'execute', None)
if execute_method is None or \
not (inspect.ismethod(execute_method) or inspect.isfunction(execute_method)):
raise ImproperlyConfigured('The "execute" method must be configured')
return new_action
def function_argument_call(func, arguments, do_thread=True):
try:
accepts = inspect.getargspec(func)[0]
except TypeError:
accepts = inspect.getargspec(func.__init__)[0]
x = {}
for val, arg in enumerate(accepts):
if val == 0 and (inspect.ismethod(func) or inspect.isclass(func)):
continue # Ingnore first argument if it is a method
x[arg] = arguments.get(arg)
if do_thread:
thread = threading.Thread(target=func, kwargs=x)
thread.daemon = True
return thread.start
call_func = lambda: func(**x)
return call_func
def command(fn, name=None):
"""Decorator for functions that should be exposed as commands."""
module = sys.modules[fn.__module__]
if name is None:
name = fn.__name__
if asyncio.iscoroutinefunction(fn if inspect.isfunction(fn) else fn.__func__ if inspect.ismethod(fn) else fn.__call__): # Get the actual function for coroutine check
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
try:
frame = inspect.currentframe()
ctx = frame.f_back.f_locals['ctx']
return await fn(ctx, *args, **kwargs)
finally:
del frame
else:
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
frame = inspect.currentframe()
ctx = frame.f_back.f_locals['ctx']
return fn(ctx, *args, **kwargs)
finally:
del frame
vars(module).setdefault('commands', {})[fn.__name__] = wrapper
return wrapper
def get_class_that_defined_method(meth):
"""Returns the class that created the given method.
A helper function for finding class methods amongst a list of many
methods.
Source:
http://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545
"""
if inspect.ismethod(meth):
for cls in inspect.getmro(meth.__self__.__class__):
if cls.__dict__.get(meth.__name__) is meth:
return cls
meth = meth.__func__ # fallback to __qualname__ parsing
if inspect.isfunction(meth):
# Check to make sure the method has a "qualname"
if not getattr(meth, '__qualname__', None):
return None
cls = getattr(inspect.getmodule(meth),
meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
if isinstance(cls, type):
return cls
return None # not required since None would have been implicitly returned anyway
def getargspec(obj):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
Modified version of inspect.getargspec from the Python Standard
Library."""
if inspect.isfunction(obj):
func_obj = obj
elif inspect.ismethod(obj):
func_obj = obj.__func__
else:
raise TypeError('arg is not a Python function')
args, varargs, varkw = inspect.getargs(func_obj.__code__)
return args, varargs, varkw, func_obj.__defaults__
#-----------------------------------------------------------------------------
# Testing functions
def dobindings(self):
members = inspect.getmembers(self.__class__, inspect.ismethod)
for methodname, method in members:
if hasattr(method, AutoBind.attrname):
event = getattr(wx, method._event_name)
boundmethod = method.__get__(self, self.__class__)
pubname = method._event_name.lower() + '.' + self.name
boundmethod = PubSend(pubname)(boundmethod)
self.widget.Bind(event, boundmethod)
# self.owner.Bind(event, boundmethod, id=self.widget.GetId())
elif hasattr(method, AutoCallback.attrname):
boundmethod = method.__get__(self, self.__class__)
attr = getattr(self.__class__, method._var_name, None)
if attr is None:
attr = getattr(self, method._var_name, None)
attr.addcallback(boundmethod)
def _subscribe(self):
def sgetter(funcname):
def realsgetter(owner, msg):
return owner._subs[funcname](owner, msg)
return realsgetter
# wx classes throw exception if getmember is applied to the instance (self)
methods = inspect.getmembers(self.__class__, inspect.ismethod)
topicmgr = pub.getDefaultTopicMgr()
for mname, method in methods:
pubsubtopic = getattr(method, '_pubrecv', None)
if pubsubtopic:
self._subs[mname] = method
subsgetter = sgetter(mname)
if (not topicmgr.getTopic(pubsubtopic, True) or
not pub.isSubscribed(subsgetter, pubsubtopic)):
setattr(self, mname, subsgetter)
pub.subscribe(subsgetter.__get__(self, self.__class__),
pubsubtopic)
def test_excluding_predicates(self):
self.istest(inspect.isbuiltin, 'sys.exit')
if check_impl_detail():
self.istest(inspect.isbuiltin, '[].append')
self.istest(inspect.iscode, 'mod.spam.__code__')
self.istest(inspect.isframe, 'tb.tb_frame')
self.istest(inspect.isfunction, 'mod.spam')
self.istest(inspect.isfunction, 'mod.StupidGit.abuse')
self.istest(inspect.ismethod, 'git.argue')
self.istest(inspect.ismodule, 'mod')
self.istest(inspect.istraceback, 'tb')
self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory')
self.istest(inspect.isgenerator, '(x for x in range(2))')
self.istest(inspect.isgeneratorfunction, 'generator_function_example')
if hasattr(types, 'GetSetDescriptorType'):
self.istest(inspect.isgetsetdescriptor,
'type(tb.tb_frame).f_locals')
else:
self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
if hasattr(types, 'MemberDescriptorType'):
self.istest(inspect.ismemberdescriptor,
'type(lambda: None).__globals__')
else:
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
def format_object(object):
"""
Returns a fully-qualified name for the specified object, such as
'landscape.lib.format.format_object()'.
"""
if inspect.ismethod(object):
# FIXME If the method is implemented on a base class of
# object's class, the module name and function name will be
# from the base class and the method's class name will be from
# object's class.
name = repr(object).split(" ")[2]
return "%s.%s()" % (object.__module__, name)
elif inspect.isfunction(object):
name = repr(object).split(" ")[1]
return "%s.%s()" % (object.__module__, name)
return "%s.%s" % (object.__class__.__module__, object.__class__.__name__)
def get_global_vars(func):
""" Store any methods or variables bound from the function's closure
Args:
func (function): function to inspect
Returns:
dict: mapping of variable names to globally bound VARIABLES
"""
closure = getclosurevars(func)
if closure['nonlocal']:
raise TypeError("Can't launch a job with closure variables: %s" %
closure['nonlocals'].keys())
globalvars = dict(modules={},
functions={},
vars={})
for name, value in closure['global'].items():
if inspect.ismodule(value): # TODO: deal FUNCTIONS from closure
globalvars['modules'][name] = value.__name__
elif inspect.isfunction(value) or inspect.ismethod(value):
globalvars['functions'][name] = value
else:
globalvars['vars'][name] = value
return globalvars