def standard_build(self): if type(self) is types.InstanceType: # old-style instance return types.InstanceType(self.__class__) else: # new-style instance return type(self).__new__(type(self))
def constructor(cls, callable): '''Return a closure that constructs the original `callable` type from a function.''' # `callable` is a function type, so just return a closure that returns it if isinstance(callable, types.FunctionType): return lambda func: func # if it's a method type, then we just need to extract the related properties to construct it elif isinstance(callable, types.MethodType): return lambda method, self=callable.im_self, cls=callable.im_class: types.MethodType( method, self, cls) # if it's a property decorator, we just need to pass the function as an argument to the decorator elif isinstance(callable, (staticmethod, classmethod)): return lambda method, mt=callable.__class__: mt(method) # if it's a method instance, then we just need to instantiate it so that it's bound elif isinstance(callable, types.InstanceType): return lambda method, mt=callable.__class__: types.InstanceType( mt, dict(method.__dict__)) # otherwise if it's a class or a type, then we just need to create the object with its bases elif isinstance(n, (types.TypeType, types.ClassType)): return lambda method, t=callable.__class__, name=callable.__name__, bases=callable.__bases__: t( name, bases, dict(method.__dict__)) # if we get here, then we have no idea what kind of type `callable` is raise internal.exceptions.InvalidTypeOrValueError(callable.__class__)
def failureFromJSON(failureDict): """ Load a L{Failure} from a dictionary deserialized from JSON. @param failureDict: a JSON-deserialized object like one previously returned by L{failureAsJSON}. @type failureDict: L{dict} mapping L{unicode} to attributes @return: L{Failure} @rtype: L{Failure} """ # InstanceType() is only available in Python 2 and lower. # __new__ is only available on new-style classes. newFailure = getattr(Failure, "__new__", None) if newFailure is None: f = types.InstanceType(Failure) else: f = newFailure(Failure) if not _PY3: # Python 2 needs the failure dictionary as purely bytes, not text failureDict = asBytes(failureDict) typeInfo = failureDict["type"] failureDict["type"] = type(typeInfo["__name__"], (), typeInfo) f.__dict__ = failureDict return f
def makewidget(master, klass, path): path = str(path) self = types.InstanceType(klass) self._name = path[len(master._w) + 1:] self._w = path self.children = {} master.children[self._name] = self self.master = master self.tk = master.tk return self
def getExplorer(self, object, identifier): oid = id(object) if oid in self.data: # XXX: This potentially returns something with # 'identifier' set to a different value. return self.data[oid] else: klass = typeTable.get(type(object), ExplorerGeneric) e = types.InstanceType(klass, {}) self.data[oid] = e klass.__init__(e, object, identifier) return e
def reconstructor(cls, n): if isinstance(n, types.FunctionType): return lambda f: f if isinstance(n, types.MethodType): return lambda f: types.MethodType(f, n.im_self, n.im_class) if isinstance(n, (staticmethod,classmethod)): return lambda f: type(n)(f) if isinstance(n, types.InstanceType): return lambda f: types.InstanceType(type(n), dict(f.__dict__)) if isinstance(n, (types.TypeType,types.ClassType)): return lambda f: type(n)(n.__name__, n.__bases__, dict(f.__dict__)) raise NotImplementedError, type(func)
def reconstructor(cls, n): '''Return a closure that returns the original callable type for a function.''' if isinstance(n, types.FunctionType): return lambda f: f if isinstance(n, types.MethodType): return lambda f: types.MethodType(f, n.im_self, n.im_class) if isinstance(n, (staticmethod, classmethod)): return lambda f: type(n)(f) if isinstance(n, types.InstanceType): return lambda f: types.InstanceType(type(n), dict(f.__dict__)) if isinstance(n, (types.TypeType, types.ClassType)): return lambda f: type(n)(n.__name__, n.__bases__, dict(f.__dict__)) raise internal.exceptions.InvalidTypeOrValueError(type(n))
def process_request(self, sock_params): # The actual request handling takes place in __init__, so we need to # set minimum_chunk_size before __init__ executes and we don't want to modify # class variable sock, address = sock_params proto = types.InstanceType(self.protocol) if self.minimum_chunk_size is not None: proto.minimum_chunk_size = self.minimum_chunk_size proto.capitalize_response_headers = self.capitalize_response_headers try: proto.__init__(sock, address, self) except socket.timeout: # Expected exceptions are not exceptional sock.close() if self.debug: # similar to logging "accepted" in server() self.log_message('(%s) timed out %r' % (self.pid, address))
def getMBeanAttribute(name, value, path): ''' Helper method to get an MBeanAttribute object. This uses the type system to access the required MBeanAttribute type, if a type is not provided then the default is to use 'MBeanAttribute'. ''' result = MBeanAttributeTypes.MBeanAttribute(name, value, path) classifier = classify(name) if classifier != None : pbTypeDict = getAttributeType(classifier) if pbTypeDict != None : attributeClass = getattr(MBeanAttributeTypes, pbTypeDict["pbAttributeType"]) attributeObj = types.InstanceType(attributeClass) attributeObj.__init__(name, value, path) attributeObj.isOffline = getBooleanAttributeFromTypeDict(pbTypeDict, "isOffline") attributeObj.isPostConfig = getBooleanAttributeFromTypeDict(pbTypeDict, "isPostConfig") attributeObj.getAttribute() result = attributeObj result.mbeanAttributePath = getMBeanPath(name) return result
def failureFromJSON(failureDict): """ Load a L{Failure} from a dictionary deserialized from JSON. @param failureDict: a JSON-deserialized object like one previously returned by L{failureAsJSON}. @type failureDict: L{dict} mapping L{unicode} to attributes @return: L{Failure} @rtype: L{Failure} """ newFailure = getattr(Failure, "__new__", None) if newFailure is None: failureDict = asBytes(failureDict) f = types.InstanceType(Failure) else: f = newFailure(Failure) typeInfo = failureDict["type"] failureDict["type"] = type(typeInfo["__name__"], (), typeInfo) f.__dict__ = failureDict return f
def instantiate(cls, nonmovable=False): "Create an empty instance of 'cls'." if isinstance(cls, type): return cls.__new__(cls) else: return types.InstanceType(cls)
def failure2Copyable(fail, unsafeTracebacks=0): f = types.InstanceType(CopyableFailure, fail.__dict__) f.unsafeTracebacks = unsafeTracebacks return f
class Server(BaseHTTPServer.HTTPServer): def __init__(self, socket, address, app, log=None, environ=None, max_http_version=None, protocol=HttpProtocol, minimum_chunk_size=None, log_x_forwarded_for=True, keepalive=True, log_output=True, log_format=DEFAULT_LOG_FORMAT, url_length_limit=MAX_REQUEST_LINE, debug=True): self.outstanding_requests = 0 self.socket = socket self.address = address if log: self.log = log else: self.log = sys.stderr self.app = app self.keepalive = keepalive self.environ = environ self.max_http_version = max_http_version self.protocol = protocol self.pid = os.getpid() self.minimum_chunk_size = minimum_chunk_size self.log_x_forwarded_for = log_x_forwarded_for self.log_output = log_output self.log_format = log_format self.url_length_limit = url_length_limit self.debug = debug def get_environ(self): d = { 'wsgi.errors': sys.stderr, 'wsgi.version': (1, 0), 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', } # detect secure socket if hasattr(self.socket, 'do_handshake'): d['wsgi.url_scheme'] = 'https' d['HTTPS'] = 'on' if self.environ is not None: d.update(self.environ) return d def process_request(self, (socket, address)): # The actual request handling takes place in __init__, so we need to # set minimum_chunk_size before __init__ executes and we don't want to modify # class variable proto = types.InstanceType(self.protocol) if self.minimum_chunk_size is not None: proto.minimum_chunk_size = self.minimum_chunk_size proto.__init__(socket, address, self)
def unjellyAO(self, ao): """Unjelly an Abstract Object and everything it contains. I return the real object. """ self.stack.append(ao) t = type(ao) if t is types.InstanceType: #Abstract Objects c = ao.__class__ if c is Module: return reflect.namedModule(ao.name) elif c in [Class, Function] or issubclass(c, type): return reflect.namedObject(ao.name) elif c is InstanceMethod: im_name = ao.name im_class = reflect.namedObject(ao.klass) im_self = self.unjellyAO(ao.instance) if im_name in im_class.__dict__: if im_self is None: return getattr(im_class, im_name) elif isinstance(im_self, crefutil.NotKnown): return crefutil._InstanceMethod( im_name, im_self, im_class) else: return types.MethodType(im_class.__dict__[im_name], im_self, im_class) else: raise TypeError("instance method changed") elif c is Instance: klass = reflect.namedObject(ao.klass) state = self.unjellyAO(ao.state) if hasattr(klass, "__setstate__"): inst = types.InstanceType(klass, {}) self.callAfter(inst.__setstate__, state) else: inst = types.InstanceType(klass, state) return inst elif c is Ref: o = self.unjellyAO(ao.obj) #THIS IS CHANGING THE REF OMG refkey = ao.refnum ref = self.references.get(refkey) if ref is None: self.references[refkey] = o elif isinstance(ref, crefutil.NotKnown): ref.resolveDependants(o) self.references[refkey] = o elif refkey is None: # This happens when you're unjellying from an AOT not read from source pass else: raise ValueError( "Multiple references with the same ID: %s, %s, %s!" % (ref, refkey, ao)) return o elif c is Deref: num = ao.refnum ref = self.references.get(num) if ref is None: der = crefutil._Dereference(num) self.references[num] = der return der return ref elif c is Copyreg: loadfunc = reflect.namedObject(ao.loadfunc) d = self.unjellyLater(ao.state).addCallback( lambda result, _l: _l(*result), loadfunc) return d #Types elif t in _SIMPLE_BUILTINS: return ao elif t is types.ListType: l = [] for x in ao: l.append(None) self.unjellyInto(l, len(l) - 1, x) return l elif t is types.TupleType: l = [] tuple_ = tuple for x in ao: l.append(None) if isinstance(self.unjellyInto(l, len(l) - 1, x), crefutil.NotKnown): tuple_ = crefutil._Tuple return tuple_(l) elif t is types.DictType: d = {} for k, v in ao.items(): kvd = crefutil._DictKeyAndValue(d) self.unjellyInto(kvd, 0, k) self.unjellyInto(kvd, 1, v) return d else: raise TypeError("Unsupported AOT type: %s" % t) del self.stack[-1]