desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get next char from raw queue. Block if no data is immediately available. Raise EOFError when connection is closed.'
def rawq_getchar(self):
if (not self.rawq): self.fill_rawq() if self.eof: raise EOFError c = self.rawq[self.irawq] self.irawq = (self.irawq + 1) if (self.irawq >= len(self.rawq)): self.rawq = '' self.irawq = 0 return c
'Fill raw queue from exactly one recv() system call. Block if no data is immediately available. Set self.eof when connection is closed.'
def fill_rawq(self):
if (self.irawq >= len(self.rawq)): self.rawq = '' self.irawq = 0 buf = self.sock.recv(50) self.msg('recv %r', buf) self.eof = (not buf) self.rawq = (self.rawq + buf)
'Test whether data is available on the socket.'
def sock_avail(self):
return (select.select([self], [], [], 0) == ([self], [], []))
'Interaction function, emulates a very dumb telnet client.'
def interact(self):
if (sys.platform == 'win32'): self.mt_interact() return while 1: (rfd, wfd, xfd) = select.select([self, sys.stdin], [], []) if (self in rfd): try: text = self.read_eager() except EOFError: print '*** Connection closed by remote host ***' break if text: sys.stdout.write(text) sys.stdout.flush() if (sys.stdin in rfd): line = sys.stdin.readline() if (not line): break self.write(line)
'Multithreaded version of interact().'
def mt_interact(self):
import thread thread.start_new_thread(self.listener, ()) while 1: line = sys.stdin.readline() if (not line): break self.write(line)
'Helper for mt_interact() -- this executes in the other thread.'
def listener(self):
while 1: try: data = self.read_eager() except EOFError: print '*** Connection closed by remote host ***' return if data: sys.stdout.write(data) else: sys.stdout.flush()
'Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of three items: the index in the list of the first regular expression that matches; the match object returned; and the text read up till and including the match. If EOF is read and no text was read, raise EOFError. Otherwise, when nothing matches, return (-1, None, text) where text is the text received so far (may be the empty string if a timeout happened). If a regular expression ends with a greedy match (e.g. \'.*\') or if more than one expression can match the same input, the results are undeterministic, and may depend on the I/O timing.'
def expect(self, list, timeout=None):
re = None list = list[:] indices = range(len(list)) for i in indices: if (not hasattr(list[i], 'search')): if (not re): import re list[i] = re.compile(list[i]) if (timeout is not None): from time import time time_start = time() while 1: self.process_rawq() for i in indices: m = list[i].search(self.cookedq) if m: e = m.end() text = self.cookedq[:e] self.cookedq = self.cookedq[e:] return (i, m, text) if self.eof: break if (timeout is not None): elapsed = (time() - time_start) if (elapsed >= timeout): break s_args = ([self.fileno()], [], [], (timeout - elapsed)) (r, w, x) = select.select(*s_args) if (not r): break self.fill_rawq() text = self.read_very_lazy() if ((not text) and self.eof): raise EOFError return ((-1), None, text)
'Builds a qualified name from a (ns_url, localname) pair'
def _qname(self, name):
if name[0]: if ('http://www.w3.org/XML/1998/namespace' == name[0]): return ('xml:' + name[1]) prefix = self._current_context[name[0]] if prefix: return ((prefix + ':') + name[1]) return name[1]
'Parse an XML document from a URL or an InputSource.'
def parse(self, source):
source = saxutils.prepare_input_source(source) self._source = source self.reset() self._cont_handler.setDocumentLocator(ExpatLocator(self)) xmlreader.IncrementalParser.parse(self, source)
'Creates an exception. The message is required, but the exception is optional.'
def __init__(self, msg, exception=None):
self._msg = msg self._exception = exception Exception.__init__(self, msg)
'Return a message for this exception.'
def getMessage(self):
return self._msg
'Return the embedded exception, or None if there was none.'
def getException(self):
return self._exception
'Create a string representation of the exception.'
def __str__(self):
return self._msg
'Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.'
def __getitem__(self, ix):
raise AttributeError('__getitem__')
'Creates the exception. The exception parameter is allowed to be None.'
def __init__(self, msg, exception, locator):
SAXException.__init__(self, msg, exception) self._locator = locator self._systemId = self._locator.getSystemId() self._colnum = self._locator.getColumnNumber() self._linenum = self._locator.getLineNumber()
'The column number of the end of the text where the exception occurred.'
def getColumnNumber(self):
return self._colnum
'The line number of the end of the text where the exception occurred.'
def getLineNumber(self):
return self._linenum
'Get the public identifier of the entity where the exception occurred.'
def getPublicId(self):
return self._locator.getPublicId()
'Get the system identifier of the entity where the exception occurred.'
def getSystemId(self):
return self._systemId
'Create a string representation of the exception.'
def __str__(self):
sysid = self.getSystemId() if (sysid is None): sysid = '<unknown>' linenum = self.getLineNumber() if (linenum is None): linenum = '?' colnum = self.getColumnNumber() if (colnum is None): colnum = '?' return ('%s:%s:%s: %s' % (sysid, linenum, colnum, self._msg))
'Parse an XML document from a system identifier or an InputSource.'
def parse(self, source):
raise NotImplementedError('This method must be implemented!')
'Returns the current ContentHandler.'
def getContentHandler(self):
return self._cont_handler
'Registers a new object to receive document content events.'
def setContentHandler(self, handler):
self._cont_handler = handler
'Returns the current DTD handler.'
def getDTDHandler(self):
return self._dtd_handler
'Register an object to receive basic DTD-related events.'
def setDTDHandler(self, handler):
self._dtd_handler = handler
'Returns the current EntityResolver.'
def getEntityResolver(self):
return self._ent_handler
'Register an object to resolve external entities.'
def setEntityResolver(self, resolver):
self._ent_handler = resolver
'Returns the current ErrorHandler.'
def getErrorHandler(self):
return self._err_handler
'Register an object to receive error-message events.'
def setErrorHandler(self, handler):
self._err_handler = handler
'Allow an application to set the locale for errors and warnings. SAX parsers are not required to provide localization for errors and warnings; if they cannot support the requested locale, however, they must throw a SAX exception. Applications may request a locale change in the middle of a parse.'
def setLocale(self, locale):
raise SAXNotSupportedException('Locale support not implemented')
'Looks up and returns the state of a SAX2 feature.'
def getFeature(self, name):
raise SAXNotRecognizedException(("Feature '%s' not recognized" % name))
'Sets the state of a SAX2 feature.'
def setFeature(self, name, state):
raise SAXNotRecognizedException(("Feature '%s' not recognized" % name))
'Looks up and returns the value of a SAX2 property.'
def getProperty(self, name):
raise SAXNotRecognizedException(("Property '%s' not recognized" % name))
'Sets the value of a SAX2 property.'
def setProperty(self, name, value):
raise SAXNotRecognizedException(("Property '%s' not recognized" % name))
'This method gives the raw XML data in the data parameter to the parser and makes it parse the data, emitting the corresponding events. It is allowed for XML constructs to be split across several calls to feed. feed may raise SAXException.'
def feed(self, data):
raise NotImplementedError('This method must be implemented!')
'This method is called by the parse implementation to allow the SAX 2.0 driver to prepare itself for parsing.'
def prepareParser(self, source):
raise NotImplementedError('prepareParser must be overridden!')
'This method is called when the entire XML document has been passed to the parser through the feed method, to notify the parser that there are no more data. This allows the parser to do the final checks on the document and empty the internal data buffer. The parser will not be ready to parse another document until the reset method has been called. close may raise SAXException.'
def close(self):
raise NotImplementedError('This method must be implemented!')
'This method is called after close has been called to reset the parser so that it is ready to parse new documents. The results of calling parse or feed after close without calling reset are undefined.'
def reset(self):
raise NotImplementedError('This method must be implemented!')
'Return the column number where the current event ends.'
def getColumnNumber(self):
return (-1)
'Return the line number where the current event ends.'
def getLineNumber(self):
return (-1)
'Return the public identifier for the current event.'
def getPublicId(self):
return None
'Return the system identifier for the current event.'
def getSystemId(self):
return None
'Sets the public identifier of this InputSource.'
def setPublicId(self, public_id):
self.__public_id = public_id
'Returns the public identifier of this InputSource.'
def getPublicId(self):
return self.__public_id
'Sets the system identifier of this InputSource.'
def setSystemId(self, system_id):
self.__system_id = system_id
'Returns the system identifier of this InputSource.'
def getSystemId(self):
return self.__system_id
'Sets the character encoding of this InputSource. The encoding must be a string acceptable for an XML encoding declaration (see section 4.3.3 of the XML recommendation). The encoding attribute of the InputSource is ignored if the InputSource also contains a character stream.'
def setEncoding(self, encoding):
self.__encoding = encoding
'Get the character encoding of this InputSource.'
def getEncoding(self):
return self.__encoding
'Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.'
def setByteStream(self, bytefile):
self.__bytefile = bytefile
'Get the byte stream for this input source. The getEncoding method will return the character encoding for this byte stream, or None if unknown.'
def getByteStream(self):
return self.__bytefile
'Set the character stream for this input source. (The stream must be a Python 2.0 Unicode-wrapped file-like that performs conversion to Unicode strings.) If there is a character stream specified, the SAX parser will ignore any byte stream and will not attempt to open a URI connection to the system identifier.'
def setCharacterStream(self, charfile):
self.__charfile = charfile
'Get the character stream for this input source.'
def getCharacterStream(self):
return self.__charfile
'Non-NS-aware implementation. attrs should be of the form {name : value}.'
def __init__(self, attrs):
self._attrs = attrs
'NS-aware implementation. attrs should be of the form {(ns_uri, lname): value, ...}. qnames of the form {(ns_uri, lname): qname, ...}.'
def __init__(self, attrs, qnames):
self._attrs = attrs self._qnames = qnames
'Handle a recoverable error.'
def error(self, exception):
raise exception
'Handle a non-recoverable error.'
def fatalError(self, exception):
raise exception
'Handle a warning.'
def warning(self, exception):
print exception
'Called by the parser to give the application a locator for locating the origin of document events. SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in the DocumentHandler interface. The locator allows the application to determine the end position of any document-related event, even if the parser is not reporting an error. Typically, the application will use this information for reporting its own errors (such as character content that does not match an application\'s business rules). The information returned by the locator is probably not sufficient for use with a search engine. Note that the locator will return correct information only during the invocation of the events in this interface. The application should not attempt to use it at any other time.'
def setDocumentLocator(self, locator):
self._locator = locator
'Resolve the system identifier of an entity and return either the system identifier to read from as a string, or an InputSource to read from.'
def resolveEntity(self, publicId, systemId):
return systemId
'Create a new parser object.'
def createParser(self):
return expat.ParserCreate()
'Return the parser object, creating a new one if needed.'
def getParser(self):
if (not self._parser): self._parser = self.createParser() self._intern_setdefault = self._parser.intern.setdefault self._parser.buffer_text = True self._parser.ordered_attributes = True self._parser.specified_attributes = True self.install(self._parser) return self._parser
'Free all data structures used during DOM construction.'
def reset(self):
self.document = theDOMImplementation.createDocument(EMPTY_NAMESPACE, None, None) self.curNode = self.document self._elem_info = self.document._elem_info self._cdata = False
'Install the callbacks needed to build the DOM into the parser.'
def install(self, parser):
parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler parser.StartElementHandler = self.first_element_handler parser.EndElementHandler = self.end_element_handler parser.ProcessingInstructionHandler = self.pi_handler if self._options.entities: parser.EntityDeclHandler = self.entity_decl_handler parser.NotationDeclHandler = self.notation_decl_handler if self._options.comments: parser.CommentHandler = self.comment_handler if self._options.cdata_sections: parser.StartCdataSectionHandler = self.start_cdata_section_handler parser.EndCdataSectionHandler = self.end_cdata_section_handler parser.CharacterDataHandler = self.character_data_handler_cdata else: parser.CharacterDataHandler = self.character_data_handler parser.ExternalEntityRefHandler = self.external_entity_ref_handler parser.XmlDeclHandler = self.xml_decl_handler parser.ElementDeclHandler = self.element_decl_handler parser.AttlistDeclHandler = self.attlist_decl_handler
'Parse a document from a file object, returning the document node.'
def parseFile(self, file):
parser = self.getParser() first_buffer = True try: while 1: buffer = file.read((16 * 1024)) if (not buffer): break parser.Parse(buffer, 0) if (first_buffer and self.document.documentElement): self._setup_subset(buffer) first_buffer = False parser.Parse('', True) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
'Parse a document from a string, returning the document node.'
def parseString(self, string):
parser = self.getParser() try: parser.Parse(string, True) self._setup_subset(string) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
'Load the internal subset if there might be one.'
def _setup_subset(self, buffer):
if self.document.doctype: extractor = InternalSubsetExtractor() extractor.parseString(buffer) subset = extractor.getSubset() self.document.doctype.internalSubset = subset
'Parse a document fragment from a file object, returning the fragment node.'
def parseFile(self, file):
return self.parseString(file.read())
'Parse a document fragment from a string, returning the fragment node.'
def parseString(self, string):
self._source = string parser = self.getParser() doctype = self.originalDocument.doctype ident = '' if doctype: subset = (doctype.internalSubset or self._getDeclarations()) if doctype.publicId: ident = ('PUBLIC "%s" "%s"' % (doctype.publicId, doctype.systemId)) elif doctype.systemId: ident = ('SYSTEM "%s"' % doctype.systemId) else: subset = '' nsattrs = self._getNSattrs() document = (_FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs)) try: parser.Parse(document, 1) except: self.reset() raise fragment = self.fragment self.reset() return fragment
'Re-create the internal subset from the DocumentType node. This is only needed if we don\'t already have the internalSubset as a string.'
def _getDeclarations(self):
doctype = self.context.ownerDocument.doctype s = '' if doctype: for i in range(doctype.notations.length): notation = doctype.notations.item(i) if s: s = (s + '\n ') s = ('%s<!NOTATION %s' % (s, notation.nodeName)) if notation.publicId: s = ('%s PUBLIC "%s"\n "%s">' % (s, notation.publicId, notation.systemId)) else: s = ('%s SYSTEM "%s">' % (s, notation.systemId)) for i in range(doctype.entities.length): entity = doctype.entities.item(i) if s: s = (s + '\n ') s = ('%s<!ENTITY %s' % (s, entity.nodeName)) if entity.publicId: s = ('%s PUBLIC "%s"\n "%s"' % (s, entity.publicId, entity.systemId)) elif entity.systemId: s = ('%s SYSTEM "%s"' % (s, entity.systemId)) else: s = ('%s "%s"' % (s, entity.firstChild.data)) if entity.notationName: s = ('%s NOTATION %s' % (s, entity.notationName)) s = (s + '>') return s
'Create a new namespace-handling parser.'
def createParser(self):
parser = expat.ParserCreate(namespace_separator=' ') parser.namespace_prefixes = True return parser
'Insert the namespace-handlers onto the parser.'
def install(self, parser):
ExpatBuilder.install(self, parser) if self._options.namespace_declarations: parser.StartNamespaceDeclHandler = self.start_namespace_decl_handler
'Push this namespace declaration on our storage.'
def start_namespace_decl_handler(self, prefix, uri):
self._ns_ordered_prefixes.append((prefix, uri))
'Return string of namespace attributes from this element and ancestors.'
def _getNSattrs(self):
attrs = '' context = self.context L = [] while context: if hasattr(context, '_ns_prefix_uri'): for (prefix, uri) in context._ns_prefix_uri.items(): if (prefix in L): continue L.append(prefix) if prefix: declname = ('xmlns:' + prefix) else: declname = 'xmlns' if attrs: attrs = ("%s\n %s='%s'" % (attrs, declname, uri)) else: attrs = (" %s='%s'" % (declname, uri)) context = context.parentNode return attrs
'Return the internal subset as a string.'
def getSubset(self):
return self.subset
'clear(): Explicitly release parsing structures'
def clear(self):
self.document = None
'Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers).'
def _slurp(self):
self.parser.parse(self.stream) self.getEvent = self._emit return self._emit()
'Fallback replacement for getEvent() that emits the events that _slurp() read previously.'
def _emit(self):
rc = self.pulldom.firstEvent[1][0] self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] return rc
'clear(): Explicitly release parsing objects'
def clear(self):
self.pulldom.clear() del self.pulldom self.parser = None self.stream = None
'Returns true iff this element is declared to have an EMPTY content model.'
def isEmpty(self):
return False
'Returns true iff the named attribute is a DTD-style ID.'
def isId(self, aname):
return False
'Returns true iff the identified attribute is a DTD-style ID.'
def isIdNS(self, namespaceURI, localName):
return False
'This method of XMLParser is deprecated.'
def doctype(self, name, pubid, system):
warnings.warn('This method of XMLParser is deprecated. Define doctype() method on the TreeBuilder target.', DeprecationWarning)
'Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, a StringIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file object. When fileobj is not None, the filename argument is only used to be included in the gzip file header, which may includes the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header. The mode argument can be any of \'r\', \'rb\', \'a\', \'ab\', \'w\', or \'wb\', depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is \'rb\'. Be aware that only the \'rb\', \'ab\', and \'wb\' values should be used for cross-platform portability. The compresslevel argument is an integer from 1 to 9 controlling the level of compression; 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression. The default is 9. The mtime argument is an optional numeric timestamp to be written to the stream when compressing. All gzip compressed streams are required to contain a timestamp. If omitted or None, the current time is used. This module ignores the timestamp when decompressing; however, some programs, such as gunzip, make use of it. The format of the timestamp is the same as that of the return value of time.time() and of the st_mtime member of the object returned by os.stat().'
def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None):
if (mode and ('b' not in mode)): mode += 'b' if (fileobj is None): fileobj = self.myfileobj = __builtin__.open(filename, (mode or 'rb')) if (filename is None): if hasattr(fileobj, 'name'): filename = fileobj.name else: filename = '' if (mode is None): if hasattr(fileobj, 'mode'): mode = fileobj.mode else: mode = 'rb' if (mode[0:1] == 'r'): self.mode = READ self._new_member = True self.extrabuf = '' self.extrasize = 0 self.extrastart = 0 self.name = filename self.min_readsize = 100 elif ((mode[0:1] == 'w') or (mode[0:1] == 'a')): self.mode = WRITE self._init_write(filename) self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, (- zlib.MAX_WBITS), zlib.DEF_MEM_LEVEL, 0) else: raise IOError, (('Mode ' + mode) + ' not supported') self.fileobj = fileobj self.offset = 0 self.mtime = mtime if (self.mode == WRITE): self._write_gzip_header()
'Raises a ValueError if the underlying file object has been closed.'
def _check_closed(self):
if self.closed: raise ValueError('I/O operation on closed file.')
'Invoke the underlying file object\'s fileno() method. This will raise AttributeError if the underlying file object doesn\'t support fileno().'
def fileno(self):
return self.fileobj.fileno()
'Return the uncompressed stream file position indicator to the beginning of the file'
def rewind(self):
if (self.mode != READ): raise IOError("Can't rewind in write mode") self.fileobj.seek(0) self._new_member = True self.extrabuf = '' self.extrasize = 0 self.extrastart = 0 self.offset = 0
'Push a token onto the stack popped by the get_token method'
def push_token(self, tok):
if (self.debug >= 1): print ('shlex: pushing token ' + repr(tok)) self.pushback.appendleft(tok)
'Push an input source onto the lexer\'s input source stack.'
def push_source(self, newstream, newfile=None):
if isinstance(newstream, basestring): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1 if self.debug: if (newfile is not None): print ('shlex: pushing to file %s' % (self.infile,)) else: print ('shlex: pushing to stream %s' % (self.instream,))
'Pop the input source stack.'
def pop_source(self):
self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() if self.debug: print ('shlex: popping to %s, line %d' % (self.instream, self.lineno)) self.state = ' '
'Get a token from the input stream (or from stack if it\'s nonempty)'
def get_token(self):
if self.pushback: tok = self.pushback.popleft() if (self.debug >= 1): print ('shlex: popping token ' + repr(tok)) return tok raw = self.read_token() if (self.source is not None): while (raw == self.source): spec = self.sourcehook(self.read_token()) if spec: (newfile, newstream) = spec self.push_source(newstream, newfile) raw = self.get_token() while (raw == self.eof): if (not self.filestack): return self.eof else: self.pop_source() raw = self.get_token() if (self.debug >= 1): if (raw != self.eof): print ('shlex: token=' + repr(raw)) else: print 'shlex: token=EOF' return raw
'Hook called on a filename to be sourced.'
def sourcehook(self, newfile):
if (newfile[0] == '"'): newfile = newfile[1:(-1)] if (isinstance(self.infile, basestring) and (not os.path.isabs(newfile))): newfile = os.path.join(os.path.dirname(self.infile), newfile) return (newfile, open(newfile, 'r'))
'Emit a C-compiler-like, Emacs-friendly error-message leader.'
def error_leader(self, infile=None, lineno=None):
if (infile is None): infile = self.infile if (lineno is None): lineno = self.lineno return ('"%s", line %d: ' % (infile, lineno))
'Register a virtual subclass of an ABC.'
def register(cls, subclass):
if (not isinstance(subclass, (type, types.ClassType))): raise TypeError('Can only register classes') if issubclass(subclass, cls): return if issubclass(cls, subclass): raise RuntimeError('Refusing to create an inheritance cycle') cls._abc_registry.add(subclass) ABCMeta._abc_invalidation_counter += 1
'Debug helper to print the ABC registry.'
def _dump_registry(cls, file=None):
print >>file, ('Class: %s.%s' % (cls.__module__, cls.__name__)) print >>file, ('Inv.counter: %s' % ABCMeta._abc_invalidation_counter) for name in sorted(cls.__dict__.keys()): if name.startswith('_abc_'): value = getattr(cls, name) print >>file, ('%s: %r' % (name, value))
'Override for isinstance(instance, cls).'
def __instancecheck__(cls, instance):
subclass = getattr(instance, '__class__', None) if ((subclass is not None) and (subclass in cls._abc_cache)): return True subtype = type(instance) if (subtype is _InstanceType): subtype = subclass if ((subtype is subclass) or (subclass is None)): if ((cls._abc_negative_cache_version == ABCMeta._abc_invalidation_counter) and (subtype in cls._abc_negative_cache)): return False return cls.__subclasscheck__(subtype) return (cls.__subclasscheck__(subclass) or cls.__subclasscheck__(subtype))
'Override for issubclass(subclass, cls).'
def __subclasscheck__(cls, subclass):
if (subclass in cls._abc_cache): return True if (cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter): cls._abc_negative_cache = WeakSet() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter elif (subclass in cls._abc_negative_cache): return False ok = cls.__subclasshook__(subclass) if (ok is not NotImplemented): assert isinstance(ok, bool) if ok: cls._abc_cache.add(subclass) else: cls._abc_negative_cache.add(subclass) return ok if (cls in getattr(subclass, '__mro__', ())): cls._abc_cache.add(subclass) return True for rcls in cls._abc_registry: if issubclass(subclass, rcls): cls._abc_cache.add(subclass) return True for scls in cls.__subclasses__(): if issubclass(subclass, scls): cls._abc_cache.add(subclass) return True cls._abc_negative_cache.add(subclass) return False
'Return true if the scope uses exec'
def has_exec(self):
return bool((self._table.optimized & (OPT_EXEC | OPT_BARE_EXEC)))
'Return true if the scope uses import *'
def has_import_star(self):
return bool((self._table.optimized & OPT_IMPORT_STAR))
'Returns true if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. Note that a single name can be bound to multiple objects. If is_namespace() is true, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace.'
def is_namespace(self):
return bool(self.__namespaces)
'Return a list of namespaces bound to this name'
def get_namespaces(self):
return self.__namespaces