desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Set a cookie if policy says it\'s OK to do so.'
def set_cookie_if_ok(self, cookie, request):
self._cookies_lock.acquire() try: self._policy._now = self._now = int(time.time()) if self._policy.set_ok(cookie, request): self.set_cookie(cookie) finally: self._cookies_lock.release()
'Set a cookie, without checking whether or not it should be set.'
def set_cookie(self, cookie):
c = self._cookies self._cookies_lock.acquire() try: if (cookie.domain not in c): c[cookie.domain] = {} c2 = c[cookie.domain] if (cookie.path not in c2): c2[cookie.path] = {} c3 = c2[cookie.path] c3[cookie.name] = cookie finally: sel...
'Extract cookies from response, where allowable given the request.'
def extract_cookies(self, response, request):
_debug('extract_cookies: %s', response.info()) self._cookies_lock.acquire() try: self._policy._now = self._now = int(time.time()) for cookie in self.make_cookies(response, request): if self._policy.set_ok(cookie, request): _debug(' setting cookie: %s',...
'Clear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified path within that domain are removed. If given three arguments, then the cookie with the spe...
def clear(self, domain=None, path=None, name=None):
if (name is not None): if ((domain is None) or (path is None)): raise ValueError('domain and path must be given to remove a cookie by name') del self._cookies[domain][path][name] elif (path is not None): if (domain is None): raise ...
'Discard all session cookies. Note that the .save() method won\'t save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.'
def clear_session_cookies(self):
self._cookies_lock.acquire() try: for cookie in self: if cookie.discard: self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
'Discard all expired cookies. You probably don\'t need to call this method: expired cookies are never sent back to the server (provided you\'re using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won\'t save expired cookies anyway (unless you ask otherwise by pas...
def clear_expired_cookies(self):
self._cookies_lock.acquire() try: now = time.time() for cookie in self: if cookie.is_expired(now): self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
'Return number of contained cookies.'
def __len__(self):
i = 0 for cookie in self: i = (i + 1) return i
'Cookies are NOT loaded from the named file until either the .load() or .revert() method is called.'
def __init__(self, filename=None, delayload=False, policy=None):
CookieJar.__init__(self, policy) if (filename is not None): try: (filename + '') except: raise ValueError('filename must be string-like') self.filename = filename self.delayload = bool(delayload)
'Save cookies to a file.'
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
raise NotImplementedError()
'Load cookies from a file.'
def load(self, filename=None, ignore_discard=False, ignore_expires=False):
if (filename is None): if (self.filename is not None): filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) f = open(filename) try: self._really_load(f, filename, ignore_discard, ignore_expires) finally: f.close()
'Clear all cookies and reload cookies from a saved file. Raises LoadError (or IOError) if reversion is not successful; the object\'s state will not be altered if this happens.'
def revert(self, filename=None, ignore_discard=False, ignore_expires=False):
if (filename is None): if (self.filename is not None): filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) self._cookies_lock.acquire() try: old_state = copy.deepcopy(self._cookies) self._cookies = {} try: self.lo...
'Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard...
def add_type(self, type, ext, strict=True):
self.types_map[strict][ext] = type exts = self.types_map_inv[strict].setdefault(type, []) if (ext not in exts): exts.append(ext)
'Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can\'t be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. c...
def guess_type(self, url, strict=True):
(scheme, url) = urllib.splittype(url) if (scheme == 'data'): comma = url.find(',') if (comma < 0): return (None, None) semi = url.find(';', 0, comma) if (semi >= 0): type = url[:semi] else: type = url[:comma] if (('=' in type) o...
'Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot (\'.\'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type\' by guess_type(). O...
def guess_all_extensions(self, type, strict=True):
type = type.lower() extensions = self.types_map_inv[True].get(type, []) if (not strict): for ext in self.types_map_inv[False].get(type, []): if (ext not in extensions): extensions.append(ext) return extensions
'Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot (\'.\'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type\' by guess_type(). If no extension can be...
def guess_extension(self, type, strict=True):
extensions = self.guess_all_extensions(type, strict) if (not extensions): return None return extensions[0]
'Read a single mime.types-format file, specified by pathname. If strict is true, information will be added to list of standard types, else to the list of non-standard types.'
def read(self, filename, strict=True):
with open(filename) as fp: self.readfp(fp, strict)
'Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types.'
def readfp(self, fp, strict=True):
while 1: line = fp.readline() if (not line): break words = line.split() for i in range(len(words)): if (words[i][0] == '#'): del words[i:] break if (not words): continue (type, suffixes) = (words[0], ...
'Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types.'
def read_windows_registry(self, strict=True):
if (not _winreg): return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break else: if ('\x00' not in ctype): (yield ctype) ...
'Generate documentation for an object.'
def document(self, object, name=None, *args):
args = ((object, name) + args) if inspect.isgetsetdescriptor(object): return self.docdata(*args) if inspect.ismemberdescriptor(object): return self.docdata(*args) try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): ...
'Raise an exception for unimplemented types.'
def fail(self, object, name=None, *args):
message = ("don't know how to document object%s of type %s" % ((name and (' ' + repr(name))), type(object).__name__)) raise TypeError, message
'Return the location of module docs or None'
def getdocloc(self, object):
try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get('PYTHONDOCS', 'http://docs.python.org/library') basedir = os.path.join(sys.exec_prefix, 'lib', ('python' + sys.version[0:3])) if (isinstance(object, type(os)) and ((object.__name__ in...
'Format an HTML page.'
def page(self, title, contents):
return _encode(('\n<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n<html><head><title>Python: %s</title>\n<meta charset="utf-8">\n</head><body bgcolor="#f0f0f8">\n%s\n</body></html>' % (title, contents)), 'ascii')
'Format a page heading.'
def heading(self, title, fgcol, bgcol, extras=''):
return ('\n<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">\n<tr bgcolor="%s">\n<td valign=bottom>&nbsp;<br>\n<font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td\n><td align=right valign=bottom\n><font color="%s" face="helvetica, ...
'Format a section with a heading.'
def section(self, title, fgcol, bgcol, contents, width=6, prelude='', marginalia=None, gap='&nbsp;'):
if (marginalia is None): marginalia = (('<tt>' + ('&nbsp;' * width)) + '</tt>') result = ('<p>\n<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">\n<tr bgcolor="%s">\n<td colspan=3 valign=bottom>&nbsp;<br>\n<font color="%s" face="helvetica, aria...
'Format a section with a big heading.'
def bigsection(self, title, *args):
title = ('<big><strong>%s</strong></big>' % title) return self.section(title, *args)
'Format literal preformatted text.'
def preformat(self, text):
text = self.escape(expandtabs(text)) return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', ' ', '&nbsp;', '\n', '<br>\n')
'Format a list of items into a multi-column list.'
def multicolumn(self, list, format, cols=4):
result = '' rows = (((len(list) + cols) - 1) // cols) for col in range(cols): result = (result + ('<td width="%d%%" valign=top>' % (100 // cols))) for i in range((rows * col), ((rows * col) + rows)): if (i < len(list)): result = ((result + format(list[i])) +...
'Make a link for an identifier, given name-to-URL mappings.'
def namelink(self, name, *dicts):
for dict in dicts: if (name in dict): return ('<a href="%s">%s</a>' % (dict[name], name)) return name
'Make a link for a class.'
def classlink(self, object, modname):
(name, module) = (object.__name__, sys.modules.get(object.__module__)) if (hasattr(module, name) and (getattr(module, name) is object)): return ('<a href="%s.html#%s">%s</a>' % (module.__name__, name, classname(object, modname))) return classname(object, modname)
'Make a link for a module.'
def modulelink(self, object):
return ('<a href="%s.html">%s</a>' % (object.__name__, object.__name__))
'Make a link for a module or package to display in an index.'
def modpkglink(self, data):
(name, path, ispackage, shadowed) = data if shadowed: return self.grey(name) if path: url = ('%s.%s.html' % (path, name)) else: url = ('%s.html' % name) if ispackage: text = ('<strong>%s</strong>&nbsp;(package)' % name) else: text = name return ('<a ...
'Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.'
def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
escape = (escape or self.escape) results = [] here = 0 pattern = re.compile('\\b((http|ftp)://\\S+[\\w/]|RFC[- ]?(\\d+)|PEP[- ]?(\\d+)|(self\\.)?(\\w+))') while True: match = pattern.search(text, here) if (not match): break (start, end) = match.span() ...
'Produce HTML for a class tree as given by inspect.getclasstree().'
def formattree(self, tree, modname, parent=None):
result = '' for entry in tree: if (type(entry) is type(())): (c, bases) = entry result = (result + '<dt><font face="helvetica, arial">') result = (result + self.classlink(c, modname)) if (bases and (bases != (parent,))): parents = [] ...
'Produce HTML documentation for a module object.'
def docmodule(self, object, name=None, mod=None, *ignored):
name = object.__name__ try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range((len(parts) - 1)): links.append(('<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:(i + 1)], '.'), parts[i]))) ...
'Produce HTML documentation for a class object.'
def docclass(self, object, name=None, mod=None, funcs={}, classes={}, *ignored):
realname = object.__name__ name = (name or realname) bases = object.__bases__ contents = [] push = contents.append class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('<hr>\n') self....
'Format an argument default value as text.'
def formatvalue(self, object):
return self.grey(('=' + self.repr(object)))
'Produce HTML documentation for a function or method object.'
def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None):
realname = object.__name__ name = (name or realname) anchor = ((((cl and cl.__name__) or '') + '-') + name) note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if (imclass is not cl): note = (' from ' + self.class...
'Produce html documentation for a property.'
def docproperty(self, object, name=None, mod=None, cl=None):
return self._docdescriptor(name, object, mod)
'Produce HTML documentation for a data object.'
def docother(self, object, name=None, mod=None, *ignored):
lhs = ((name and ('<strong>%s</strong> = ' % name)) or '') return (lhs + self.repr(object))
'Produce html documentation for a data descriptor.'
def docdata(self, object, name=None, mod=None, cl=None):
return self._docdescriptor(name, object, mod)
'Generate an HTML index for a directory of modules.'
def index(self, dir, shadowed=None):
modpkgs = [] if (shadowed is None): shadowed = {} for (importer, name, ispkg) in pkgutil.iter_modules([dir]): modpkgs.append((name, '', ispkg, (name in shadowed))) shadowed[name] = 1 modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) return self.bigsecti...
'Format a string in bold by overstriking.'
def bold(self, text):
return join(map((lambda ch: ((ch + '\x08') + ch)), text), '')
'Indent text by prepending a given prefix to each line.'
def indent(self, text, prefix=' '):
if (not text): return '' lines = split(text, '\n') lines = map((lambda line, prefix=prefix: (prefix + line)), lines) if lines: lines[(-1)] = rstrip(lines[(-1)]) return join(lines, '\n')
'Format a section with a given heading.'
def section(self, title, contents):
return (((self.bold(title) + '\n') + rstrip(self.indent(contents))) + '\n\n')
'Render in text a class tree as returned by inspect.getclasstree().'
def formattree(self, tree, modname, parent=None, prefix=''):
result = '' for entry in tree: if (type(entry) is type(())): (c, bases) = entry result = ((result + prefix) + classname(c, modname)) if (bases and (bases != (parent,))): parents = map((lambda c, m=modname: classname(c, m)), bases) resul...
'Produce text documentation for a given module object.'
def docmodule(self, object, name=None, mod=None):
name = object.__name__ (synop, desc) = splitdoc(getdoc(object)) result = self.section('NAME', (name + (synop and (' - ' + synop)))) try: all = object.__all__ except AttributeError: all = None try: file = inspect.getabsfile(object) except TypeError: file ...
'Produce text documentation for a given class object.'
def docclass(self, object, name=None, mod=None, *ignored):
realname = object.__name__ name = (name or realname) bases = object.__bases__ def makename(c, m=object.__module__): return classname(c, m) if (name == realname): title = ('class ' + self.bold(realname)) else: title = ((self.bold(name) + ' = class ') + realname...
'Format an argument default value as text.'
def formatvalue(self, object):
return ('=' + self.repr(object))
'Produce text documentation for a function or method object.'
def docroutine(self, object, name=None, mod=None, cl=None):
realname = object.__name__ name = (name or realname) note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if (imclass is not cl): note = (' from ' + classname(imclass, mod)) elif (object.im_self is not None): ...
'Produce text documentation for a property.'
def docproperty(self, object, name=None, mod=None, cl=None):
return self._docdescriptor(name, object, mod)
'Produce text documentation for a data descriptor.'
def docdata(self, object, name=None, mod=None, cl=None):
return self._docdescriptor(name, object, mod)
'Produce text documentation for a data object.'
def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
repr = self.repr(object) if maxlen: line = (((name and (name + ' = ')) or '') + repr) chop = (maxlen - len(line)) if (chop < 0): repr = (repr[:chop] + '...') line = (((name and (self.bold(name) + ' = ')) or '') + repr) if (doc is not None): line +=...
'Read one line, using raw_input when available.'
def getline(self, prompt):
if (self.input is sys.stdin): return raw_input(prompt) else: self.output.write(prompt) self.output.flush() return self.input.readline()
'Return scope of name. The scope of a name could be LOCAL, GLOBAL, FREE, or CELL.'
def check_name(self, name):
if (name in self.globals): return SC_GLOBAL_EXPLICIT if (name in self.cells): return SC_CELL if (name in self.defs): return SC_LOCAL if (self.nested and ((name in self.frees) or (name in self.uses))): return SC_FREE if self.nested: return SC_UNKNOWN else: ...
'Force name to be global in scope. Some child of the current node had a free reference to name. When the child was processed, it was labelled a free variable. Now that all its enclosing scope have been processed, the name is known to be a global or builtin. So walk back down the child chain and set the name to be glo...
def force_global(self, name):
self.globals[name] = 1 if (name in self.frees): del self.frees[name] for child in self.children: if (child.check_name(name) == SC_FREE): child.force_global(name)
'Process list of free vars from nested scope. Returns a list of names that are either 1) declared global in the parent or 2) undefined in a top-level parent. In either case, the nested scope should treat them as globals.'
def add_frees(self, names):
child_globals = [] for name in names: sc = self.check_name(name) if self.nested: if ((sc == SC_UNKNOWN) or (sc == SC_FREE) or isinstance(self, ClassScope)): self.frees[name] = 1 elif (sc == SC_GLOBAL_IMPLICIT): child_globals.append(name) ...
'Propagate assignment flag down to child nodes. The Assign node doesn\'t itself contains the variables being assigned to. Instead, the children in node.nodes are visited with the assign flag set to true. When the names occur in those nodes, they are marked as defs. Some names that occur in an assignment target are no...
def visitAssign(self, node, scope):
for n in node.nodes: self.visit(n, scope, 1) self.visit(node.expr, scope)
'Verify that class is constructed correctly'
def checkClass(self):
try: assert hasattr(self, 'graph') assert getattr(self, 'NameFinder') assert getattr(self, 'FunctionGen') assert getattr(self, 'ClassGen') except AssertionError as msg: intro = ('Bad class construction for %s' % self.__class__.__name__) raise Assertion...
'Return a code object'
def getCode(self):
return self.graph.getCode()
'Emit name ops for names generated implicitly by for loops The interpreter generates names that start with a period or dollar sign. The symbol table ignores these names because they aren\'t present in the program text.'
def _implicitNameOp(self, prefix, name):
if self.optimized: self.emit((prefix + '_FAST'), name) else: self.emit((prefix + '_NAME'), name)
'Emit SET_LINENO if necessary. The instruction is considered necessary if the node has a lineno attribute and it is different than the last lineno emitted. Returns true if SET_LINENO was emitted. There are no rules for when an AST node should have a lineno attribute. The transformer and AST code need to be reviewed an...
def set_lineno(self, node, force=False):
lineno = getattr(node, 'lineno', None) if ((lineno is not None) and ((lineno != self.last_lineno) or force)): self.emit('SET_LINENO', lineno) self.last_lineno = lineno return True return False
'Transform an AST into a modified parse tree.'
def transform(self, tree):
if (not (isinstance(tree, tuple) or isinstance(tree, list))): tree = parser.st2tuple(tree, line_info=1) return self.compile_node(tree)
'Return a modified parse tree for the given suite text.'
def parsesuite(self, text):
return self.transform(parser.suite(text))
'Return a modified parse tree for the given expression text.'
def parseexpr(self, text):
return self.transform(parser.expr(text))
'Return a modified parse tree for the contents of the given file.'
def parsefile(self, file):
if (type(file) == type('')): file = open(file) return self.parsesuite(file.read())
'Return node suitable for lvalue of augmented assignment Names, slices, and attributes are the only allowable nodes.'
def com_augassign(self, node):
l = self.com_node(node) if (l.__class__ in (Name, Slice, Subscript, Getattr)): return l raise SyntaxError, ("can't assign to %s" % l.__class__.__name__)
'Compile \'NODE (OP NODE)*\' into (type, [ node1, ..., nodeN ]).'
def com_binary(self, constructor, nodelist):
l = len(nodelist) if (l == 1): n = nodelist[0] return self.lookup_node(n)(n[1:]) items = [] for i in range(0, l, 2): n = nodelist[i] items.append(self.lookup_node(n)(n[1:])) return constructor(items, lineno=extractLineNo(nodelist))
'Do preorder walk of tree using visitor'
def preorder(self, tree, visitor, *args):
self.visitor = visitor visitor.visit = self.dispatch self.dispatch(tree, *args)
'Return list of features enabled by future statements'
def get_features(self):
return self.found.keys()
'Return the blocks in reverse postorder i.e. each node appears before all of its successors'
def getBlocksInOrder(self):
order = order_blocks(self.entry, self.exit) return order
'Return nodes appropriate for use with dominator'
def getRoot(self):
return self.entry
'Returns True if there is an unconditional transfer to an other block at the end of this block. This means there is no risk for the bytecode executer to go past this block\'s bytecode.'
def has_unconditional_transfer(self):
try: (op, arg) = self.insts[(-1)] except (IndexError, ValueError): return return (op in self._uncond_transfer)
'Get the whole list of followers, including the next block.'
def get_followers(self):
followers = set(self.next) for inst in self.insts: if (inst[0] in PyFlowGraph.hasjrel): followers.add(inst[1]) return followers
'Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body.'
def getContainedGraphs(self):
contained = [] for inst in self.insts: if (len(inst) == 1): continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained
'Get a Python code object'
def getCode(self):
assert (self.stage == RAW) self.computeStackDepth() self.flattenGraph() assert (self.stage == FLAT) self.convertArgs() assert (self.stage == CONV) self.makeByteCode() assert (self.stage == DONE) return self.newCodeObject()
'Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect.'
def computeStackDepth(self):
depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if (b in seen): return d seen[b] = 1 d = (d + depth[b]) children = b.get_children() if children: return m...
'Arrange the blocks in order and resolve jumps'
def flattenGraph(self):
assert (self.stage == RAW) self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if (len(inst) == 1): pc = (pc + 1) elif (inst[0] !...
'Convert arguments from symbolic to concrete form'
def convertArgs(self):
assert (self.stage == FLAT) self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if (len(t) == 2): (opname, oparg) = t conv = self._converters.get(opname, None) if conv: self.inst...
'Sort cellvars in the order of varnames and prune from freevars.'
def sort_cellvars(self):
cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if (name in cells)] for name in self.cellvars: del cells[name] self.cellvars = (self.cellvars + cells.keys()) self.closure = (self.cellvars + self.freevars)
'Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can\'t store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before co...
def _lookupName(self, name, list):
t = type(name) for i in range(len(list)): if ((t == type(list[i])) and (list[i] == name)): return i end = len(list) list.append(name) return end
'Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively.'
def getConsts(self):
l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l)
'Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first.'
def __init__(self, multi=None):
self.multi = multi self.errors = 0
'Create a new mutex -- initially unlocked.'
def __init__(self):
self.locked = False self.queue = deque()
'Test the locked bit of the mutex.'
def test(self):
return self.locked
'Atomic test-and-set -- grab the lock if it is not set, return True if it succeeded.'
def testandset(self):
if (not self.locked): self.locked = True return True else: return False
'Lock a mutex, call the function with supplied argument when it is acquired. If the mutex is already locked, place function and argument in the queue.'
def lock(self, function, argument):
if self.testandset(): function(argument) else: self.queue.append((function, argument))
'Unlock a mutex. If the queue is not empty, call the next function with its argument.'
def unlock(self):
if self.queue: (function, argument) = self.queue.popleft() function(argument) else: self.locked = False
'Handle pretty printing operations onto a stream using a set of configured parameters. indent Number of spaces to indent for each level of nesting. width Attempted maximum number of columns in the output. depth The maximum depth to print out nested structures. stream The desired output stream. If omitted (or false), t...
def __init__(self, indent=1, width=80, depth=None, stream=None):
indent = int(indent) width = int(width) assert (indent >= 0), 'indent must be >= 0' assert ((depth is None) or (depth > 0)), 'depth must be > 0' assert width, 'width must be != 0' self._depth = depth self._indent_per_level = indent self._width = width ...
'Format object for a specific context, returning a string and flags indicating whether the representation is \'readable\' and whether the object represents a recursive construct.'
def format(self, object, context, maxlevels, level):
return _safe_repr(object, context, maxlevels, level)
'Run the callback unless it has already been called or cancelled'
def __call__(self, wr=None):
try: del _finalizer_registry[self._key] except KeyError: sub_debug('finalizer no longer registered') else: if (self._pid != os.getpid()): sub_debug('finalizer ignored because different process') res = None else: sub_deb...
'Cancel finalization of the object'
def cancel(self):
try: del _finalizer_registry[self._key] except KeyError: pass else: self._weakref = self._callback = self._args = self._kwargs = self._key = None
'Return whether this finalizer is still waiting to invoke callback'
def still_active(self):
return (self._key in _finalizer_registry)
'Method to be run in sub-process; can be overridden in sub-class'
def run(self):
if self._target: self._target(*self._args, **self._kwargs)
'Start child process'
def start(self):
assert (self._popen is None), 'cannot start a process twice' assert (self._parent_pid == os.getpid()), 'can only start a process object created by current process' assert (not _current_process._daemonic), 'daemonic processes are not allowed to have ...
'Terminate process; sends SIGTERM signal or uses TerminateProcess()'
def terminate(self):
self._popen.terminate()
'Wait until child process terminates'
def join(self, timeout=None):
assert (self._parent_pid == os.getpid()), 'can only join a child process' assert (self._popen is not None), 'can only join a started process' res = self._popen.wait(timeout) if (res is not None): _current_process._children.discard(self)
'Return whether process is alive'
def is_alive(self):
if (self is _current_process): return True assert (self._parent_pid == os.getpid()), 'can only test a child process' if (self._popen is None): return False self._popen.poll() return (self._popen.returncode is None)
'Return whether process is a daemon'
@property def daemon(self):
return self._daemonic
'Set whether process is a daemon'
@daemon.setter def daemon(self, daemonic):
assert (self._popen is None), 'process has already started' self._daemonic = daemonic
'Set authorization key of process'
@authkey.setter def authkey(self, authkey):
self._authkey = AuthenticationString(authkey)