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:
self._cookies_lock.release()
|
'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', cookie)
self.set_cookie(cookie)
finally:
self._cookies_lock.release()
|
'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 specified name, path and domain is removed.
Raises KeyError if no matching cookie exists.'
| 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 ValueError('domain must be given to remove cookies by path')
del self._cookies[domain][path]
elif (domain is not None):
del self._cookies[domain]
else:
self._cookies = {}
|
'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 passing a true ignore_expires argument).'
| 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.load(filename, ignore_discard, ignore_expires)
except (LoadError, IOError):
self._cookies = old_state
raise
finally:
self._cookies_lock.release()
|
'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
types.'
| 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. compress or gzip). The
mappings are table driven. Encoding suffixes are case
sensitive; type suffixes are first tried case sensitive, then
case insensitive.
The suffixes .tgz, .taz and .tz (case sensitive!) are all
mapped to \'.tar.gz\'. (This is table-driven too, using the
dictionary suffix_map.)
Optional `strict\' argument when False adds a bunch of commonly found,
but non-standard types.'
| 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) or ('/' not in type)):
type = 'text/plain'
return (type, None)
(base, ext) = posixpath.splitext(url)
while (ext in self.suffix_map):
(base, ext) = posixpath.splitext((base + self.suffix_map[ext]))
if (ext in self.encodings_map):
encoding = self.encodings_map[ext]
(base, ext) = posixpath.splitext(base)
else:
encoding = None
types_map = self.types_map[True]
if (ext in types_map):
return (types_map[ext], encoding)
elif (ext.lower() in types_map):
return (types_map[ext.lower()], encoding)
elif strict:
return (None, encoding)
types_map = self.types_map[False]
if (ext in types_map):
return (types_map[ext], encoding)
elif (ext.lower() in types_map):
return (types_map[ext.lower()], encoding)
else:
return (None, encoding)
|
'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().
Optional `strict\' argument when false adds a bunch of commonly found,
but non-standard types.'
| 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 guessed for `type\', None
is returned.
Optional `strict\' argument when false adds a bunch of commonly found,
but non-standard types.'
| 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], words[1:])
for suff in suffixes:
self.add_type(type, ('.' + suff), strict)
|
'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)
i += 1
default_encoding = sys.getdefaultencoding()
with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr:
for subkeyname in enum_types(hkcr):
try:
with _winreg.OpenKey(hkcr, subkeyname) as subkey:
if (not subkeyname.startswith('.')):
continue
(mimetype, datatype) = _winreg.QueryValueEx(subkey, 'Content Type')
if (datatype != _winreg.REG_SZ):
continue
try:
mimetype = mimetype.encode(default_encoding)
except UnicodeEncodeError:
continue
self.add_type(mimetype, subkeyname, strict)
except EnvironmentError:
continue
|
'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):
return self.docclass(*args)
if inspect.isroutine(object):
return self.docroutine(*args)
except AttributeError:
pass
if isinstance(object, property):
return self.docproperty(*args)
return self.docother(*args)
|
'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 ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport')) or (file.startswith(basedir) and (not file.startswith(os.path.join(basedir, 'site-packages'))))) and (object.__name__ not in ('xml.etree', 'test.pydoc_mod'))):
if docloc.startswith('http://'):
docloc = ('%s/%s' % (docloc.rstrip('/'), object.__name__))
else:
docloc = os.path.join(docloc, (object.__name__ + '.html'))
else:
docloc = None
return docloc
|
'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> <br>\n<font color="%s" face="helvetica, arial"> <br>%s</font></td\n><td align=right valign=bottom\n><font color="%s" face="helvetica, arial">%s</font></td></tr></table>\n ' % (bgcol, fgcol, title, fgcol, (extras or ' ')))
|
'Format a section with a heading.'
| def section(self, title, fgcol, bgcol, contents, width=6, prelude='', marginalia=None, gap=' '):
| if (marginalia is None):
marginalia = (('<tt>' + (' ' * 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> <br>\n<font color="%s" face="helvetica, arial">%s</font></td></tr>\n ' % (bgcol, fgcol, title))
if prelude:
result = (result + ('\n<tr bgcolor="%s"><td rowspan=2>%s</td>\n<td colspan=2>%s</td></tr>\n<tr><td>%s</td>' % (bgcol, marginalia, prelude, gap)))
else:
result = (result + ('\n<tr><td bgcolor="%s">%s</td><td>%s</td>' % (bgcol, marginalia, gap)))
return (result + ('\n<td width="100%%">%s</td></tr></table>' % contents))
|
'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', ' ', ' ', '\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])) + '<br>\n')
result = (result + '</td>')
return ('<table width="100%%" summary="list"><tr>%s</tr></table>' % result)
|
'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> (package)' % name)
else:
text = name
return ('<a href="%s">%s</a>' % (url, text))
|
'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()
results.append(escape(text[here:start]))
(all, scheme, rfc, pep, selfdot, name) = match.groups()
if scheme:
url = escape(all).replace('"', '"')
results.append(('<a href="%s">%s</a>' % (url, url)))
elif rfc:
url = ('http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc))
results.append(('<a href="%s">%s</a>' % (url, escape(all))))
elif pep:
url = ('http://www.python.org/dev/peps/pep-%04d/' % int(pep))
results.append(('<a href="%s">%s</a>' % (url, escape(all))))
elif selfdot:
if (text[end:(end + 1)] == '('):
results.append(('self.' + self.namelink(name, methods)))
else:
results.append(('self.<strong>%s</strong>' % name))
elif (text[end:(end + 1)] == '('):
results.append(self.namelink(name, methods, funcs, classes))
else:
results.append(self.namelink(name, classes))
here = end
results.append(escape(text[here:]))
return join(results, '')
|
'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 = []
for base in bases:
parents.append(self.classlink(base, modname))
result = (((result + '(') + join(parents, ', ')) + ')')
result = (result + '\n</font></dt>')
elif (type(entry) is type([])):
result = (result + ('<dd>\n%s</dd>\n' % self.formattree(entry, modname, c)))
return ('<dl>\n%s</dl>\n' % result)
|
'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])))
linkedname = join((links + parts[(-1):]), '.')
head = ('<big><big><strong>%s</strong></big></big>' % linkedname)
try:
path = inspect.getabsfile(object)
url = path
if (sys.platform == 'win32'):
import nturl2path
url = nturl2path.pathname2url(path)
filelink = ('<a href="file:%s">%s</a>' % (url, path))
except TypeError:
filelink = '(built-in)'
info = []
if hasattr(object, '__version__'):
version = _binstr(object.__version__)
if ((version[:11] == ('$' + 'Revision: ')) and (version[(-1):] == '$')):
version = strip(version[11:(-1)])
info.append(('version %s' % self.escape(version)))
if hasattr(object, '__date__'):
info.append(self.escape(_binstr(object.__date__)))
if info:
head = (head + (' (%s)' % join(info, ', ')))
docloc = self.getdocloc(object)
if (docloc is not None):
docloc = ('<br><a href="%(docloc)s">Module Docs</a>' % locals())
else:
docloc = ''
result = self.heading(head, '#ffffff', '#7799ee', (('<a href=".">index</a><br>' + filelink) + docloc))
modules = inspect.getmembers(object, inspect.ismodule)
(classes, cdict) = ([], {})
for (key, value) in inspect.getmembers(object, inspect.isclass):
if ((all is not None) or ((inspect.getmodule(value) or object) is object)):
if visiblename(key, all, object):
classes.append((key, value))
cdict[key] = cdict[value] = ('#' + key)
for (key, value) in classes:
for base in value.__bases__:
(key, modname) = (base.__name__, base.__module__)
module = sys.modules.get(modname)
if ((modname != name) and module and hasattr(module, key)):
if (getattr(module, key) is base):
if (not (key in cdict)):
cdict[key] = cdict[base] = ((modname + '.html#') + key)
(funcs, fdict) = ([], {})
for (key, value) in inspect.getmembers(object, inspect.isroutine):
if ((all is not None) or inspect.isbuiltin(value) or (inspect.getmodule(value) is object)):
if visiblename(key, all, object):
funcs.append((key, value))
fdict[key] = ('#-' + key)
if inspect.isfunction(value):
fdict[value] = fdict[key]
data = []
for (key, value) in inspect.getmembers(object, isdata):
if visiblename(key, all, object):
data.append((key, value))
doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
doc = (doc and ('<tt>%s</tt>' % doc))
result = (result + ('<p>%s</p>\n' % doc))
if hasattr(object, '__path__'):
modpkgs = []
for (importer, modname, ispkg) in pkgutil.iter_modules(object.__path__):
modpkgs.append((modname, name, ispkg, 0))
modpkgs.sort()
contents = self.multicolumn(modpkgs, self.modpkglink)
result = (result + self.bigsection('Package Contents', '#ffffff', '#aa55cc', contents))
elif modules:
contents = self.multicolumn(modules, (lambda key_value, s=self: s.modulelink(key_value[1])))
result = (result + self.bigsection('Modules', '#ffffff', '#aa55cc', contents))
if classes:
classlist = map((lambda key_value: key_value[1]), classes)
contents = [self.formattree(inspect.getclasstree(classlist, 1), name)]
for (key, value) in classes:
contents.append(self.document(value, key, name, fdict, cdict))
result = (result + self.bigsection('Classes', '#ffffff', '#ee77aa', join(contents)))
if funcs:
contents = []
for (key, value) in funcs:
contents.append(self.document(value, key, name, fdict, cdict))
result = (result + self.bigsection('Functions', '#ffffff', '#eeaa77', join(contents)))
if data:
contents = []
for (key, value) in data:
contents.append(self.document(value, key))
result = (result + self.bigsection('Data', '#ffffff', '#55aa55', join(contents, '<br>\n')))
if hasattr(object, '__author__'):
contents = self.markup(_binstr(object.__author__), self.preformat)
result = (result + self.bigsection('Author', '#ffffff', '#7799ee', contents))
if hasattr(object, '__credits__'):
contents = self.markup(_binstr(object.__credits__), self.preformat)
result = (result + self.bigsection('Credits', '#ffffff', '#7799ee', contents))
return result
|
'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.needone = 1
hr = HorizontalRule()
mro = deque(inspect.getmro(object))
if (len(mro) > 2):
hr.maybe()
push('<dl><dt>Method resolution order:</dt>\n')
for base in mro:
push(('<dd>%s</dd>\n' % self.classlink(base, object.__module__)))
push('</dl>\n')
def spill(msg, attrs, predicate):
(ok, attrs) = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for (name, kind, homecls, value) in ok:
try:
value = getattr(object, name)
except Exception:
push(self._docdescriptor(name, value, mod))
else:
push(self.document(value, name, mod, funcs, classes, mdict, object))
push('\n')
return attrs
def spilldescriptors(msg, attrs, predicate):
(ok, attrs) = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for (name, kind, homecls, value) in ok:
push(self._docdescriptor(name, value, mod))
return attrs
def spilldata(msg, attrs, predicate):
(ok, attrs) = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for (name, kind, homecls, value) in ok:
base = self.docother(getattr(object, name), name, mod)
if (hasattr(value, '__call__') or inspect.isdatadescriptor(value)):
doc = getattr(value, '__doc__', None)
else:
doc = None
if (doc is None):
push(('<dl><dt>%s</dl>\n' % base))
else:
doc = self.markup(getdoc(value), self.preformat, funcs, classes, mdict)
doc = ('<dd><tt>%s</tt>' % doc)
push(('<dl><dt>%s%s</dl>\n' % (base, doc)))
push('\n')
return attrs
attrs = filter((lambda data: visiblename(data[0], obj=object)), classify_class_attrs(object))
mdict = {}
for (key, kind, homecls, value) in attrs:
mdict[key] = anchor = ((('#' + name) + '-') + key)
try:
value = getattr(object, name)
except Exception:
pass
try:
mdict[value] = anchor
except TypeError:
pass
while attrs:
if mro:
thisclass = mro.popleft()
else:
thisclass = attrs[0][2]
(attrs, inherited) = _split_list(attrs, (lambda t: (t[2] is thisclass)))
if (thisclass is __builtin__.object):
attrs = inherited
continue
elif (thisclass is object):
tag = 'defined here'
else:
tag = ('inherited from %s' % self.classlink(thisclass, object.__module__))
tag += ':<br>\n'
try:
attrs.sort(key=(lambda t: t[0]))
except TypeError:
attrs.sort((lambda t1, t2: cmp(t1[0], t2[0])))
attrs = spill(('Methods %s' % tag), attrs, (lambda t: (t[1] == 'method')))
attrs = spill(('Class methods %s' % tag), attrs, (lambda t: (t[1] == 'class method')))
attrs = spill(('Static methods %s' % tag), attrs, (lambda t: (t[1] == 'static method')))
attrs = spilldescriptors(('Data descriptors %s' % tag), attrs, (lambda t: (t[1] == 'data descriptor')))
attrs = spilldata(('Data and other attributes %s' % tag), attrs, (lambda t: (t[1] == 'data')))
assert (attrs == [])
attrs = inherited
contents = ''.join(contents)
if (name == realname):
title = ('<a name="%s">class <strong>%s</strong></a>' % (name, realname))
else:
title = ('<strong>%s</strong> = <a name="%s">class %s</a>' % (name, name, realname))
if bases:
parents = []
for base in bases:
parents.append(self.classlink(base, object.__module__))
title = (title + ('(%s)' % join(parents, ', ')))
doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
doc = (doc and ('<tt>%s<br> </tt>' % doc))
return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
|
'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.classlink(imclass, mod))
elif (object.im_self is not None):
note = (' method of %s instance' % self.classlink(object.im_self.__class__, mod))
else:
note = (' unbound %s method' % self.classlink(imclass, mod))
object = object.im_func
if (name == realname):
title = ('<a name="%s"><strong>%s</strong></a>' % (anchor, realname))
else:
if (cl and (realname in cl.__dict__) and (cl.__dict__[realname] is object)):
reallink = ('<a href="#%s">%s</a>' % (((cl.__name__ + '-') + realname), realname))
skipdocs = 1
else:
reallink = realname
title = ('<a name="%s"><strong>%s</strong></a> = %s' % (anchor, name, reallink))
if inspect.isfunction(object):
(args, varargs, varkw, defaults) = inspect.getargspec(object)
argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue=self.formatvalue)
if (realname == '<lambda>'):
title = ('<strong>%s</strong> <em>lambda</em> ' % name)
argspec = argspec[1:(-1)]
else:
argspec = '(...)'
decl = ((title + argspec) + (note and self.grey(('<font face="helvetica, arial">%s</font>' % note))))
if skipdocs:
return ('<dl><dt>%s</dt></dl>\n' % decl)
else:
doc = self.markup(getdoc(object), self.preformat, funcs, classes, methods)
doc = (doc and ('<dd><tt>%s</tt></dd>' % doc))
return ('<dl><dt>%s</dt>%s</dl>\n' % (decl, doc))
|
'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.bigsection(dir, '#ffffff', '#ee77aa', contents)
|
'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)
result = (result + ('(%s)' % join(parents, ', ')))
result = (result + '\n')
elif (type(entry) is type([])):
result = (result + self.formattree(entry, modname, c, (prefix + ' ')))
return result
|
'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 = '(built-in)'
result = (result + self.section('FILE', file))
docloc = self.getdocloc(object)
if (docloc is not None):
result = (result + self.section('MODULE DOCS', docloc))
if desc:
result = (result + self.section('DESCRIPTION', desc))
classes = []
for (key, value) in inspect.getmembers(object, inspect.isclass):
if ((all is not None) or ((inspect.getmodule(value) or object) is object)):
if visiblename(key, all, object):
classes.append((key, value))
funcs = []
for (key, value) in inspect.getmembers(object, inspect.isroutine):
if ((all is not None) or inspect.isbuiltin(value) or (inspect.getmodule(value) is object)):
if visiblename(key, all, object):
funcs.append((key, value))
data = []
for (key, value) in inspect.getmembers(object, isdata):
if visiblename(key, all, object):
data.append((key, value))
modpkgs = []
modpkgs_names = set()
if hasattr(object, '__path__'):
for (importer, modname, ispkg) in pkgutil.iter_modules(object.__path__):
modpkgs_names.add(modname)
if ispkg:
modpkgs.append((modname + ' (package)'))
else:
modpkgs.append(modname)
modpkgs.sort()
result = (result + self.section('PACKAGE CONTENTS', join(modpkgs, '\n')))
submodules = []
for (key, value) in inspect.getmembers(object, inspect.ismodule):
if (value.__name__.startswith((name + '.')) and (key not in modpkgs_names)):
submodules.append(key)
if submodules:
submodules.sort()
result = (result + self.section('SUBMODULES', join(submodules, '\n')))
if classes:
classlist = map((lambda key_value: key_value[1]), classes)
contents = [self.formattree(inspect.getclasstree(classlist, 1), name)]
for (key, value) in classes:
contents.append(self.document(value, key, name))
result = (result + self.section('CLASSES', join(contents, '\n')))
if funcs:
contents = []
for (key, value) in funcs:
contents.append(self.document(value, key, name))
result = (result + self.section('FUNCTIONS', join(contents, '\n')))
if data:
contents = []
for (key, value) in data:
contents.append(self.docother(value, key, name, maxlen=70))
result = (result + self.section('DATA', join(contents, '\n')))
if hasattr(object, '__version__'):
version = _binstr(object.__version__)
if ((version[:11] == ('$' + 'Revision: ')) and (version[(-1):] == '$')):
version = strip(version[11:(-1)])
result = (result + self.section('VERSION', version))
if hasattr(object, '__date__'):
result = (result + self.section('DATE', _binstr(object.__date__)))
if hasattr(object, '__author__'):
result = (result + self.section('AUTHOR', _binstr(object.__author__)))
if hasattr(object, '__credits__'):
result = (result + self.section('CREDITS', _binstr(object.__credits__)))
return result
|
'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)
if bases:
parents = map(makename, bases)
title = (title + ('(%s)' % join(parents, ', ')))
doc = getdoc(object)
contents = ((doc and [(doc + '\n')]) or [])
push = contents.append
mro = deque(inspect.getmro(object))
if (len(mro) > 2):
push('Method resolution order:')
for base in mro:
push((' ' + makename(base)))
push('')
class HorizontalRule:
def __init__(self):
self.needone = 0
def maybe(self):
if self.needone:
push(('-' * 70))
self.needone = 1
hr = HorizontalRule()
def spill(msg, attrs, predicate):
(ok, attrs) = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for (name, kind, homecls, value) in ok:
try:
value = getattr(object, name)
except Exception:
push(self._docdescriptor(name, value, mod))
else:
push(self.document(value, name, mod, object))
return attrs
def spilldescriptors(msg, attrs, predicate):
(ok, attrs) = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for (name, kind, homecls, value) in ok:
push(self._docdescriptor(name, value, mod))
return attrs
def spilldata(msg, attrs, predicate):
(ok, attrs) = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for (name, kind, homecls, value) in ok:
if (hasattr(value, '__call__') or inspect.isdatadescriptor(value)):
doc = getdoc(value)
else:
doc = None
push((self.docother(getattr(object, name), name, mod, maxlen=70, doc=doc) + '\n'))
return attrs
attrs = filter((lambda data: visiblename(data[0], obj=object)), classify_class_attrs(object))
while attrs:
if mro:
thisclass = mro.popleft()
else:
thisclass = attrs[0][2]
(attrs, inherited) = _split_list(attrs, (lambda t: (t[2] is thisclass)))
if (thisclass is __builtin__.object):
attrs = inherited
continue
elif (thisclass is object):
tag = 'defined here'
else:
tag = ('inherited from %s' % classname(thisclass, object.__module__))
attrs.sort()
attrs = spill(('Methods %s:\n' % tag), attrs, (lambda t: (t[1] == 'method')))
attrs = spill(('Class methods %s:\n' % tag), attrs, (lambda t: (t[1] == 'class method')))
attrs = spill(('Static methods %s:\n' % tag), attrs, (lambda t: (t[1] == 'static method')))
attrs = spilldescriptors(('Data descriptors %s:\n' % tag), attrs, (lambda t: (t[1] == 'data descriptor')))
attrs = spilldata(('Data and other attributes %s:\n' % tag), attrs, (lambda t: (t[1] == 'data')))
assert (attrs == [])
attrs = inherited
contents = '\n'.join(contents)
if (not contents):
return (title + '\n')
return (((title + '\n') + self.indent(rstrip(contents), ' | ')) + '\n')
|
'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):
note = (' method of %s instance' % classname(object.im_self.__class__, mod))
else:
note = (' unbound %s method' % classname(imclass, mod))
object = object.im_func
if (name == realname):
title = self.bold(realname)
else:
if (cl and (realname in cl.__dict__) and (cl.__dict__[realname] is object)):
skipdocs = 1
title = ((self.bold(name) + ' = ') + realname)
if inspect.isfunction(object):
(args, varargs, varkw, defaults) = inspect.getargspec(object)
argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue=self.formatvalue)
if (realname == '<lambda>'):
title = (self.bold(name) + ' lambda ')
argspec = argspec[1:(-1)]
else:
argspec = '(...)'
decl = ((title + argspec) + note)
if skipdocs:
return (decl + '\n')
else:
doc = (getdoc(object) or '')
return ((decl + '\n') + (doc and (rstrip(self.indent(doc)) + '\n')))
|
'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 += ('\n' + self.indent(str(doc)))
return 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:
return SC_GLOBAL_IMPLICIT
|
'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 global
rather than free.
Be careful to stop if a child does not think the name is
free.'
| 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)
elif (isinstance(self, FunctionScope) and (sc == SC_LOCAL)):
self.cells[name] = 1
elif (sc != SC_CELL):
child_globals.append(name)
elif (sc == SC_LOCAL):
self.cells[name] = 1
elif (sc != SC_CELL):
child_globals.append(name)
return child_globals
|
'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 not bound by
the assignment, e.g. a name occurring inside a slice. The
visitor handles these nodes specially; they do not propagate
the assign flag to their children.'
| 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 AssertionError, intro
|
'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
and a consistent policy implemented and documented. Until
then, this method works around missing line numbers.'
| 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 max([max_depth(c, d) for c in children])
elif (not (b.label == 'exit')):
return max_depth(self.exit, d)
else:
return d
self.stacksize = max_depth(self.entry, 0)
|
'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] != 'SET_LINENO'):
pc = (pc + 3)
end[b] = pc
pc = 0
for i in range(len(insts)):
inst = insts[i]
if (len(inst) == 1):
pc = (pc + 1)
elif (inst[0] != 'SET_LINENO'):
pc = (pc + 3)
opname = inst[0]
if (opname in self.hasjrel):
oparg = inst[1]
offset = (begin[oparg] - pc)
insts[i] = (opname, offset)
elif (opname in self.hasjabs):
insts[i] = (opname, begin[inst[1]])
self.stage = FLAT
|
'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.insts[i] = (opname, conv(self, oparg))
self.stage = CONV
|
'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 comparing the values.'
| 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), the standard
output stream available at construction will be used.'
| 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
if (stream is not None):
self._stream = stream
else:
self._stream = _sys.stdout
|
'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_debug('finalizer calling %s with args %s and kwargs %s', self._callback, self._args, self._kwargs)
res = self._callback(*self._args, **self._kwargs)
self._weakref = self._callback = self._args = self._kwargs = self._key = None
return res
|
'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 children'
_cleanup()
if (self._Popen is not None):
Popen = self._Popen
else:
from .forking import Popen
self._popen = Popen(self)
_current_process._children.add(self)
|
'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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.