def filterwarnings(action, message="", category=Warning, module="", lineno=0,
append=0):
"""Insert an entry into the list of warnings filters (at the front).
'action' -- one of "error", "ignore", "always", "default", "module",
or "once"
'message' -- a regex that the warning message must match
'category' -- a class that the warning must be a subclass of
'module' -- a regex that the module name must match
'lineno' -- an integer line number, 0 matches all warnings
'append' -- if true, append to the list of filters
"""
import re
assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %r" % (action,)
assert isinstance(message, basestring), "message must be a string"
assert isinstance(category, (type, types.ClassType)), \
"category must be a class"
assert issubclass(category, Warning), "category must be a Warning subclass"
assert isinstance(module, basestring), "module must be a string"
assert isinstance(lineno, int) and lineno >= 0, \
"lineno must be an int >= 0"
item = (action, re.compile(message, re.I), category,
re.compile(module), lineno)
if append:
filters.append(item)
else:
filters.insert(0, item)
python类ClassType()的实例源码
def pickle(ob_type, pickle_function, constructor_ob=None):
if type(ob_type) is _ClassType:
raise TypeError("copy_reg is not intended for use with classes")
if not hasattr(pickle_function, '__call__'):
raise TypeError("reduction functions must be callable")
dispatch_table[ob_type] = pickle_function
# The constructor_ob function is a vestige of safe for unpickling.
# There is no reason for the caller to pass it anymore.
if constructor_ob is not None:
constructor(constructor_ob)
def register(cls, subclass):
"""Register a virtual subclass of an ABC."""
if not isinstance(subclass, (type, types.ClassType)):
raise TypeError("Can only register classes")
if issubclass(subclass, cls):
return # Already a subclass
# Subtle: test for cycles *after* testing for "already a subclass";
# this means we allow X.register(X) and interpret it as a no-op.
if issubclass(cls, subclass):
# This would create a cycle, which is bad for the algorithm below
raise RuntimeError("Refusing to create an inheritance cycle")
cls._abc_registry.add(subclass)
ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result
def _get_service_func(self, method, params):
"""
@raise InvalidServiceMethodError: Calls to private methods are not
allowed.
@raise UnknownServiceMethodError: Unknown method.
@raise InvalidServiceMethodError: Service method must be callable.
"""
service = None
if isinstance(self.service, (type, types.ClassType)):
service = self.service()
else:
service = self.service
if method is not None:
method = str(method)
if method.startswith('_'):
raise InvalidServiceMethodError(
"Calls to private methods are not allowed")
try:
func = getattr(service, method)
except AttributeError:
raise UnknownServiceMethodError(
"Unknown method %s" % str(method))
if not python.callable(func):
raise InvalidServiceMethodError(
"Service method %s must be callable" % str(method))
return func
if not python.callable(service):
raise UnknownServiceMethodError(
"Unknown method %s" % str(self.service))
return service
def register_entry_points_plugins(entry_point="girlfriend.plugin"):
"""???entry_point??????????????
:param entry_point: ?????entry_point
"""
global plugin_manager
third_party_plugin_mgr = extension.ExtensionManager(
namespace=entry_point, invoke_on_load=False)
for ext in third_party_plugin_mgr:
plugin_object, plugin = ext.plugin, None
# ??????
if isinstance(plugin_object, Plugin):
plugin = plugin_object
# ????
elif isinstance(plugin_object, types.ModuleType):
plugin = Plugin.wrap_module(plugin_object)
# ????
elif isinstance(plugin_object, types.FunctionType):
plugin = Plugin.wrap_function(
ext.name, plugin_object.__doc__, plugin_object)
# ???
elif isinstance(plugin_object, (types.ClassType, types.TypeType)):
plugin = Plugin.wrap_class(plugin_object)
# ?????????
else:
raise InvalidPluginException(
u"?? '{}' ??? '{}'????".format(
ext.name,
type(plugin_object).__name__)
)
plugin_manager.register(plugin)
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result
def skip(reason):
"""
Unconditionally skip a test.
"""
def decorator(test_item):
if not isinstance(test_item, (type, types.ClassType)):
@functools.wraps(test_item)
def skip_wrapper(*args, **kwargs):
raise SkipTest(reason)
test_item = skip_wrapper
test_item.__unittest_skip__ = True
test_item.__unittest_skip_why__ = reason
return test_item
return decorator
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result
def isinst(inst,clazz):
if type(inst) != types.InstanceType or type(clazz)!=types.ClassType:
return isinstance(inst,clazz)
cl = inst.__class__
cl2 = getcurrent(cl)
clazz = getcurrent(clazz)
if issubclass(cl2,clazz):
if cl == cl2:
return WAS
else:
inst.__class__ = cl2
return IS
else:
return ISNT
def __call__(self, request, node, model, viewName):
"""Get a name from my namespace.
"""
from twisted.web.woven import widgets
if viewName == "None":
return widgets.DefaultWidget(model)
vc = getattr(self.namespace, viewName, None)
# don't call modules and random crap in the namespace, only widgets
if vc and isinstance(vc, (type, ClassType)) and issubclass(vc, widgets.Widget):
return vc(model)
def loadClass(self, klass):
"""
Given a class which contains test cases, return a sorted list of
C{TestCase} instances.
"""
if not (isinstance(klass, type) or isinstance(klass, types.ClassType)):
raise TypeError("%r is not a class" % (klass,))
if not isTestCase(klass):
raise ValueError("%r is not a test case" % (klass,))
names = self.getTestCaseNames(klass)
tests = self.sort([self._makeCase(klass, self.methodPrefix+name)
for name in names])
return self.suiteFactory(tests)
def instance(klass, d):
if isinstance(klass, types.ClassType):
return new.instance(klass, d)
elif isinstance(klass, type):
o = object.__new__(klass)
o.__dict__ = d
return o
else:
raise TypeError, "%s is not a class" % klass
def _maybeClass(classnamep):
try:
object
except NameError:
isObject = 0
else:
isObject = isinstance(classnamep, type)
if isinstance(classnamep, ClassType) or isObject:
return qual(classnamep)
return classnamep
def setUnjellyableForClassTree(module, baseClass, prefix=None):
"""
Set all classes in a module derived from C{baseClass} as copiers for
a corresponding remote class.
When you have a heirarchy of Copyable (or Cacheable) classes on
one side, and a mirror structure of Copied (or RemoteCache)
classes on the other, use this to setCopierForClass all your
Copieds for the Copyables.
Each copyTag (the \"classname\" argument to getTypeToCopyFor, and
what the Copyable's getTypeToCopyFor returns) is formed from
adding a prefix to the Copied's class name. The prefix defaults
to module.__name__. If you wish the copy tag to consist of solely
the classname, pass the empty string \'\'.
@param module: a module object from which to pull the Copied classes.
(passing sys.modules[__name__] might be useful)
@param baseClass: the base class from which all your Copied classes derive.
@param prefix: the string prefixed to classnames to form the
unjellyableRegistry.
"""
if prefix is None:
prefix = module.__name__
if prefix:
prefix = "%s." % prefix
for i in dir(module):
i_ = getattr(module, i)
if type(i_) == types.ClassType:
if issubclass(i_, baseClass):
setUnjellyableForClass('%s%s' % (prefix, i), i_)
def _unjelly_class(self, rest):
clist = string.split(rest[0], '.')
modName = string.join(clist[:-1], '.')
if not self.taster.isModuleAllowed(modName):
raise InsecureJelly("module %s not allowed" % modName)
klaus = namedObject(rest[0])
if type(klaus) is not types.ClassType:
raise InsecureJelly("class %s unjellied to something that isn't a class: %s" % (repr(rest[0]), repr(klaus)))
if not self.taster.isClassAllowed(klaus):
raise InsecureJelly("class not allowed: %s" % qual(klaus))
return klaus