desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Simple shortcut for start_write + write + end_write.'
| def simple_write(self, s, frame, node=None):
| self.start_write(frame, node)
self.write(s)
self.end_write(frame)
|
'Visit a list of nodes as block in a frame. If the current frame
is no buffer a dummy ``if 0: yield None`` is written automatically
unless the force_generator parameter is set to False.'
| def blockvisit(self, nodes, frame):
| if (frame.buffer is None):
self.writeline('if 0: yield None')
else:
self.writeline('pass')
try:
for node in nodes:
self.visit(node, frame)
except CompilerExit:
pass
|
'Write a string into the output stream.'
| def write(self, x):
| if self._new_lines:
if (not self._first_write):
self.stream.write(('\n' * self._new_lines))
self.code_lineno += self._new_lines
if (self._write_debug_info is not None):
self.debug_info.append((self._write_debug_info, self.code_lineno))
self... |
'Combination of newline and write.'
| def writeline(self, x, node=None, extra=0):
| self.newline(node, extra)
self.write(x)
|
'Add one or more newlines before the next write.'
| def newline(self, node=None, extra=0):
| self._new_lines = max(self._new_lines, (1 + extra))
if ((node is not None) and (node.lineno != self._last_line)):
self._write_debug_info = node.lineno
self._last_line = node.lineno
|
'Writes a function call to the stream for the current node.
A leading comma is added automatically. The extra keyword
arguments may not include python keywords otherwise a syntax
error could occour. The extra keyword arguments should be given
as python dict.'
| def signature(self, node, frame, extra_kwargs=None):
| kwarg_workaround = False
for kwarg in chain((x.key for x in node.kwargs), (extra_kwargs or ())):
if is_python_keyword(kwarg):
kwarg_workaround = True
break
for arg in node.args:
self.write(', ')
self.visit(arg, frame)
if (not kwarg_workaround):
... |
'Pull all the references identifiers into the local scope.'
| def pull_locals(self, frame):
| for name in frame.identifiers.undeclared:
self.writeline(('l_%s = context.resolve(%r)' % (name, name)))
|
'Pull all the dependencies.'
| def pull_dependencies(self, nodes):
| visitor = DependencyFinderVisitor()
for node in nodes:
visitor.visit(node)
for dependency in ('filters', 'tests'):
mapping = getattr(self, dependency)
for name in getattr(visitor, dependency):
if (name not in mapping):
mapping[name] = self.temporary_identi... |
'Disable Python optimizations for the frame.'
| def unoptimize_scope(self, frame):
| if frame.identifiers.declared:
self.writeline(('%sdummy(%s)' % (((unoptimize_before_dead_code and 'if 0: ') or ''), ', '.join((('l_' + name) for name in frame.identifiers.declared)))))
|
'This function returns all the shadowed variables in a dict
in the form name: alias and will write the required assignments
into the current scope. No indentation takes place.
This also predefines locally declared variables from the loop
body because under some circumstances it may be the case that
`extra_vars` is pas... | def push_scope(self, frame, extra_vars=()):
| aliases = {}
for name in frame.find_shadowed(extra_vars):
aliases[name] = ident = self.temporary_identifier()
self.writeline(('%s = l_%s' % (ident, name)))
to_declare = set()
for name in frame.identifiers.declared_locally:
if (name not in aliases):
to_declare.ad... |
'Restore all aliases and delete unused variables.'
| def pop_scope(self, aliases, frame):
| for (name, alias) in aliases.iteritems():
self.writeline(('l_%s = %s' % (name, alias)))
to_delete = set()
for name in frame.identifiers.declared_locally:
if (name not in aliases):
to_delete.add(('l_' + name))
if to_delete:
self.writeline((' = '.join(to_del... |
'In Jinja a few statements require the help of anonymous
functions. Those are currently macros and call blocks and in
the future also recursive loops. As there is currently
technical limitation that doesn\'t allow reading and writing a
variable in a scope where the initial value is coming from an
outer scope, this fu... | def function_scoping(self, node, frame, children=None, find_special=True):
| if (children is None):
children = node.iter_child_nodes()
children = list(children)
func_frame = frame.inner()
func_frame.inspect(children)
overriden_closure_vars = ((func_frame.identifiers.undeclared & func_frame.identifiers.declared) & (func_frame.identifiers.declared_locally | func_frame.... |
'Dump the function def of a macro or call block.'
| def macro_body(self, node, frame, children=None):
| frame = self.function_scoping(node, frame, children)
frame.require_output_check = False
args = frame.arguments
if ('loop' in frame.identifiers.declared):
args = (args + ['l_loop=l_loop'])
self.writeline(('def macro(%s):' % ', '.join(args)), node)
self.indent()
self.buffer(frame... |
'Dump the macro definition for the def created by macro_body.'
| def macro_def(self, node, frame):
| arg_tuple = ', '.join((repr(x.name) for x in node.args))
name = getattr(node, 'name', None)
if (len(node.args) == 1):
arg_tuple += ','
self.write(('Macro(environment, macro, %r, (%s), (' % (name, arg_tuple)))
for arg in node.defaults:
self.visit(arg, frame)
sel... |
'Return a human readable position for the node.'
| def position(self, node):
| rv = ('line %d' % node.lineno)
if (self.name is not None):
rv += (' in ' + repr(self.name))
return rv
|
'Call a block and register it for the template.'
| def visit_Block(self, node, frame):
| level = 1
if frame.toplevel:
if self.has_known_extends:
return
if (self.extends_so_far > 0):
self.writeline('if parent_template is None:')
self.indent()
level += 1
context = ((node.scoped and 'context.derived(locals())') or 'context')
... |
'Calls the extender.'
| def visit_Extends(self, node, frame):
| if (not frame.toplevel):
self.fail('cannot use extend from a non top-level scope', node.lineno)
if (self.extends_so_far > 0):
if (not self.has_known_extends):
self.writeline('if parent_template is not None:')
self.indent()
self.wri... |
'Handles includes.'
| def visit_Include(self, node, frame):
| if node.with_context:
self.unoptimize_scope(frame)
if node.ignore_missing:
self.writeline('try:')
self.indent()
func_name = 'get_or_select_template'
if isinstance(node.template, nodes.Const):
if isinstance(node.template.value, basestring):
func_name = 'get_tem... |
'Visit regular imports.'
| def visit_Import(self, node, frame):
| if node.with_context:
self.unoptimize_scope(frame)
self.writeline(('l_%s = ' % node.target), node)
if frame.toplevel:
self.write(('context.vars[%r] = ' % node.target))
self.write('environment.get_template(')
self.visit(node.template, frame)
self.write((', %r).' % s... |
'Visit named imports.'
| def visit_FromImport(self, node, frame):
| self.newline(node)
self.write('included_template = environment.get_template(')
self.visit(node.template, frame)
self.write((', %r).' % self.name))
if node.with_context:
self.write('make_module(context.parent, True)')
else:
self.write('module')
var_names = []
d... |
'Helper callback.'
| def _cache_support(self, name, timeout, caller):
| key = (self.environment.fragment_cache_prefix + name)
rv = self.environment.fragment_cache.get(key)
if (rv is not None):
return rv
rv = caller()
self.environment.fragment_cache.add(key, rv, timeout)
return rv
|
'Return the total number of headers, including duplicates.'
| def __len__(self):
| return len(self._headers)
|
'Set the value of a header.'
| def __setitem__(self, name, val):
| del self[name]
self._headers.append((name, val))
|
'Delete all occurrences of a header, if present.
Does *not* raise an exception if the header is missing.'
| def __delitem__(self, name):
| name = name.lower()
self._headers[:] = [kv for kv in self._headers if (kv[0].lower() != name)]
|
'Get the first header value for \'name\'
Return None if the header is missing instead of raising an exception.
Note that if the header appeared multiple times, the first exactly which
occurrance gets returned is undefined. Use getall() to get all
the values matching a header field name.'
| def __getitem__(self, name):
| return self.get(name)
|
'Return true if the message contains the header.'
| def has_key(self, name):
| return (self.get(name) is not None)
|
'Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original header
list or were added to this instance, and may contain duplicates. Any
fields deleted and re-inserted are always appended to the header list.
If no fields exist with the given name, returns an emp... | def get_all(self, name):
| name = name.lower()
return [kv[1] for kv in self._headers if (kv[0].lower() == name)]
|
'Get the first header value for \'name\', or return \'default\''
| def get(self, name, default=None):
| name = name.lower()
for (k, v) in self._headers:
if (k.lower() == name):
return v
return default
|
'Return a list of all the header field names.
These will be sorted in the order they appeared in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.'
| def keys(self):
| return [k for (k, v) in self._headers]
|
'Return a list of all header values.
These will be sorted in the order they appeared in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.'
| def values(self):
| return [v for (k, v) in self._headers]
|
'Get all the header fields and values.
These will be sorted in the order they were in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.'
| def items(self):
| return self._headers[:]
|
'str() returns the formatted headers, complete with end line,
suitable for direct HTTP transmission.'
| def __str__(self):
| return '\r\n'.join(([('%s: %s' % kv) for kv in self._headers] + ['', '']))
|
'Return first matching header value for \'name\', or \'value\'
If there is no header named \'name\', add a new header with name \'name\'
and value \'value\'.'
| def setdefault(self, name, value):
| result = self.get(name)
if (result is None):
self._headers.append((name, value))
return value
else:
return result
|
'Extended header setting.
_name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added.
Example:
h.add_header(\... | def add_header(self, _name, _value, **_params):
| parts = []
if (_value is not None):
parts.append(_value)
for (k, v) in _params.items():
if (v is None):
parts.append(k.replace('_', '-'))
else:
parts.append(_formatparam(k.replace('_', '-'), v))
self._headers.append((_name, '; '.join(parts)))
|
'Invoke the application'
| def run(self, application):
| try:
self.setup_environ()
self.result = application(self.environ, self.start_response)
self.finish_response()
except:
try:
self.handle_error()
except:
self.close()
raise
|
'Set up the environment for one request'
| def setup_environ(self):
| env = self.environ = self.os_environ.copy()
self.add_cgi_vars()
env['wsgi.input'] = self.get_stdin()
env['wsgi.errors'] = self.get_stderr()
env['wsgi.version'] = self.wsgi_version
env['wsgi.run_once'] = self.wsgi_run_once
env['wsgi.url_scheme'] = self.get_scheme()
env['wsgi.multithread']... |
'Send any iterable data, then close self and the iterable
Subclasses intended for use in asynchronous servers will
want to redefine this method, such that it sets up callbacks
in the event loop to iterate over the data, and to call
\'self.close()\' once the response is finished.'
| def finish_response(self):
| if ((not self.result_is_file()) and (not self.sendfile())):
for data in self.result:
self.write(data)
self.finish_content()
self.close()
|
'Return the URL scheme being used'
| def get_scheme(self):
| return guess_scheme(self.environ)
|
'Compute Content-Length or switch to chunked encoding if possible'
| def set_content_length(self):
| try:
blocks = len(self.result)
except (TypeError, AttributeError, NotImplementedError):
pass
else:
if (blocks == 1):
self.headers['Content-Length'] = str(self.bytes_sent)
return
|
'Make any necessary header changes or defaults
Subclasses can extend this to add other defaults.'
| def cleanup_headers(self):
| if (not self.headers.has_key('Content-Length')):
self.set_content_length()
|
'\'start_response()\' callable as specified by PEP 333'
| def start_response(self, status, headers, exc_info=None):
| if exc_info:
try:
if self.headers_sent:
raise exc_info[0], exc_info[1], exc_info[2]
finally:
exc_info = None
elif (self.headers is not None):
raise AssertionError('Headers already set!')
assert (type(status) is StringType), 'Status mus... |
'Transmit version/status/date/server, via self._write()'
| def send_preamble(self):
| if self.origin_server:
if self.client_is_modern():
self._write(('HTTP/%s %s\r\n' % (self.http_version, self.status)))
if (not self.headers.has_key('Date')):
self._write(('Date: %s\r\n' % time.asctime(time.gmtime(time.time()))))
if (self.server_softwa... |
'\'write()\' callable as specified by PEP 333'
| def write(self, data):
| assert (type(data) is StringType), 'write() argument must be string'
if (not self.status):
raise AssertionError('write() before start_response()')
elif (not self.headers_sent):
self.bytes_sent = len(data)
self.send_headers()
else:
self.bytes_sent += len(... |
'Platform-specific file transmission
Override this method in subclasses to support platform-specific
file transmission. It is only called if the application\'s
return iterable (\'self.result\') is an instance of
\'self.wsgi_file_wrapper\'.
This method should return a true value if it was able to actually
transmit the ... | def sendfile(self):
| return False
|
'Ensure headers and content have both been sent'
| def finish_content(self):
| if (not self.headers_sent):
self.headers['Content-Length'] = '0'
self.send_headers()
else:
pass
|
'Transmit headers to the client, via self._write()'
| def send_headers(self):
| self.cleanup_headers()
self.headers_sent = True
if ((not self.origin_server) or self.client_is_modern()):
self.send_preamble()
self._write(str(self.headers))
|
'True if \'self.result\' is an instance of \'self.wsgi_file_wrapper\''
| def result_is_file(self):
| wrapper = self.wsgi_file_wrapper
return ((wrapper is not None) and isinstance(self.result, wrapper))
|
'True if client can accept status and headers'
| def client_is_modern(self):
| return (self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9')
|
'Log the \'exc_info\' tuple in the server log
Subclasses may override to retarget the output or change its format.'
| def log_exception(self, exc_info):
| try:
from traceback import print_exception
stderr = self.get_stderr()
print_exception(exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr)
stderr.flush()
finally:
exc_info = None
|
'Log current error, and send error output to client if possible'
| def handle_error(self):
| self.log_exception(sys.exc_info())
if (not self.headers_sent):
self.result = self.error_output(self.environ, self.start_response)
self.finish_response()
|
'Override server_bind to store the server name.'
| def server_bind(self):
| try:
HTTPServer.server_bind(self)
except Exception as e:
raise WSGIServerException, e
self.setup_environ()
|
'Handle a single HTTP request'
| def handle(self):
| self.raw_requestline = self.rfile.readline()
if (not self.parse_request()):
return
handler = ServerHandler(self.rfile, self.wfile, self.get_stderr(), self.get_environ())
handler.request_handler = self
handler.run(self.server.get_app())
|
'Returns the path to the media file on disk for the given URL.
The passed URL is assumed to begin with ADMIN_MEDIA_PREFIX. If the
resultant file path is outside the media directory, then a ValueError
is raised.'
| def file_path(self, url):
| relative_url = url[len(self.media_url):]
relative_path = urllib.url2pathname(relative_url)
return safe_join(self.media_dir, relative_path)
|
'Forbids multi-line headers, to prevent header injection.'
| def __setitem__(self, name, val):
| if (('\n' in val) or ('\r' in val)):
raise BadHeaderError, ("Header values can't contain newlines (got %r for header %r)" % (val, name))
if (name == 'Subject'):
val = Header(val, settings.DEFAULT_CHARSET)
MIMEText.__setitem__(self, name, val)
|
'Populate middleware lists from settings.MIDDLEWARE_CLASSES.
Must be called after the environment is fixed (see __call__).'
| def load_middleware(self):
| from django.conf import settings
from django.core import exceptions
self._request_middleware = []
self._view_middleware = []
self._response_middleware = []
self._exception_middleware = []
for middleware_path in settings.MIDDLEWARE_CLASSES:
try:
dot = middleware_path.rinde... |
'Returns an HttpResponse object for the given HttpRequest'
| def get_response(self, request):
| from django.core import exceptions, urlresolvers
from django.core.mail import mail_admins
from django.conf import settings
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
return response
urlconf = getattr(request, 'url... |
'Helper function to return the traceback as a string'
| def _get_traceback(self, exc_info=None):
| import traceback
return '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info())))
|
'Populates self._post and self._files'
| def _load_post_and_files(self):
| if (self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart')):
(self._post, self._files) = http.parse_file_upload(self._req.headers_in, self.raw_post_data)
else:
(self._post, self._files) = (http.QueryDict(self.raw_post_data), datastructures.M... |
'Lazy loader that returns self.META dictionary'
| def _get_meta(self):
| if (not hasattr(self, '_meta')):
self._meta = {'AUTH_TYPE': self._req.ap_auth_type, 'CONTENT_LENGTH': self._req.clength, 'CONTENT_TYPE': self._req.content_type, 'GATEWAY_INTERFACE': 'CGI/1.1', 'PATH_INFO': self._req.path_info, 'PATH_TRANSLATED': None, 'QUERY_STRING': self._req.args, 'REMOTE_ADDR': self._req... |
'Does page $page_number have a \'next\' page?'
| def has_next_page(self, page_number):
| return (page_number < (self.pages - 1))
|
'Returns the 1-based index of the first object on the given page,
relative to total objects found (hits).'
| def first_on_page(self, page_number):
| page_number = self.validate_page_number(page_number)
return ((self.num_per_page * page_number) + 1)
|
'Returns the 1-based index of the last object on the given page,
relative to total objects found (hits).'
| def last_on_page(self, page_number):
| page_number = self.validate_page_number(page_number)
page_number += 1
if (page_number == self.pages):
return self.hits
return (page_number * self.num_per_page)
|
'Serialize a queryset.'
| def serialize(self, queryset, **options):
| self.options = options
self.stream = options.get('stream', StringIO())
self.selected_fields = options.get('fields')
self.start_serialization()
for obj in queryset:
self.start_object(obj)
for field in obj._meta.fields:
if field.serialize:
if (field.rel is N... |
'Convert a field\'s value to a string.'
| def get_string_value(self, obj, field):
| if isinstance(field, models.DateTimeField):
value = getattr(obj, field.name).strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(field, models.FileField):
value = getattr(obj, ('get_%s_url' % field.name), (lambda : None))()
else:
value = field.flatten_data(follow=None, obj=obj).get(fiel... |
'Called when serializing of the queryset starts.'
| def start_serialization(self):
| raise NotImplementedError
|
'Called when serializing of the queryset ends.'
| def end_serialization(self):
| pass
|
'Called when serializing of an object starts.'
| def start_object(self, obj):
| raise NotImplementedError
|
'Called when serializing of an object ends.'
| def end_object(self, obj):
| pass
|
'Called to handle each individual (non-relational) field on an object.'
| def handle_field(self, obj, field):
| raise NotImplementedError
|
'Called to handle a ForeignKey field.'
| def handle_fk_field(self, obj, field):
| raise NotImplementedError
|
'Called to handle a ManyToManyField.'
| def handle_m2m_field(self, obj, field):
| raise NotImplementedError
|
'Return the fully serialized queryset.'
| def getvalue(self):
| return self.stream.getvalue()
|
'Init this serializer given a stream or a string'
| def __init__(self, stream_or_string, **options):
| self.options = options
if isinstance(stream_or_string, basestring):
self.stream = StringIO(stream_or_string)
else:
self.stream = stream_or_string
models.get_apps()
|
'Iteration iterface -- return the next item in the stream'
| def next(self):
| raise NotImplementedError
|
'Start serialization -- open the XML document and the root element.'
| def start_serialization(self):
| self.xml = SimplerXMLGenerator(self.stream, self.options.get('encoding', settings.DEFAULT_CHARSET))
self.xml.startDocument()
self.xml.startElement('django-objects', {'version': '1.0'})
|
'End serialization -- end the document.'
| def end_serialization(self):
| self.indent(0)
self.xml.endElement('django-objects')
self.xml.endDocument()
|
'Called as each object is handled.'
| def start_object(self, obj):
| if (not hasattr(obj, '_meta')):
raise base.SerializationError(('Non-model object (%s) encountered during serialization' % type(obj)))
self.indent(1)
self.xml.startElement('object', {'pk': str(obj._get_pk_val()), 'model': str(obj._meta)})
|
'Called after handling all fields for an object.'
| def end_object(self, obj):
| self.indent(1)
self.xml.endElement('object')
|
'Called to handle each field on an object (except for ForeignKeys and
ManyToManyFields)'
| def handle_field(self, obj, field):
| self.indent(2)
self.xml.startElement('field', {'name': field.name, 'type': field.get_internal_type()})
if (getattr(obj, field.name) is not None):
value = self.get_string_value(obj, field)
self.xml.characters(str(value))
else:
self.xml.addQuickElement('None')
self.xml.endEleme... |
'Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields).'
| def handle_fk_field(self, obj, field):
| self._start_relational_field(field)
related = getattr(obj, field.name)
if (related is not None):
self.xml.characters(str(related._get_pk_val()))
else:
self.xml.addQuickElement('None')
self.xml.endElement('field')
|
'Called to handle a ManyToManyField. Related objects are only
serialized as references to the object\'s PK (i.e. the related *data*
is not dumped, just the relation).'
| def handle_m2m_field(self, obj, field):
| self._start_relational_field(field)
for relobj in getattr(obj, field.name).iterator():
self.xml.addQuickElement('object', attrs={'pk': str(relobj._get_pk_val())})
self.xml.endElement('field')
|
'Helper to output the <field> element for relational fields'
| def _start_relational_field(self, field):
| self.indent(2)
self.xml.startElement('field', {'name': field.name, 'rel': field.rel.__class__.__name__, 'to': str(field.rel.to._meta)})
|
'Convert an <object> node to a DeserializedObject.'
| def _handle_object(self, node):
| Model = self._get_model_from_node(node, 'model')
pk = node.getAttribute('pk')
if (not pk):
raise base.DeserializationError("<object> node is missing the 'pk' attribute")
data = {Model._meta.pk.attname: Model._meta.pk.to_python(pk)}
m2m_data = {}
for field_node in node.g... |
'Handle a <field> node for a ForeignKey'
| def _handle_fk_field_node(self, node, field):
| if ((len(node.childNodes) == 1) and (node.childNodes[0].nodeName == 'None')):
return None
else:
return field.rel.to._meta.pk.to_python(getInnerText(node).strip().encode(self.encoding))
|
'Handle a <field> node for a ManyToManyField'
| def _handle_m2m_field_node(self, node, field):
| return [field.rel.to._meta.pk.to_python(c.getAttribute('pk').encode(self.encoding)) for c in node.getElementsByTagName('object')]
|
'Helper to look up a model from a <object model=...> or a <field
rel=... to=...> node.'
| def _get_model_from_node(self, node, attr):
| model_identifier = node.getAttribute(attr)
if (not model_identifier):
raise base.DeserializationError(("<%s> node is missing the required '%s' attribute" % (node.nodeName, attr)))
try:
Model = models.get_model(*model_identifier.split('.'))
except TypeError:
M... |
'Fetch a given key from the cache. If the key does not exist, return
default, which itself defaults to None.'
| def get(self, key, default=None):
| raise NotImplementedError
|
'Set a value in the cache. If timeout is given, that timeout will be
used for the key; otherwise the default cache timeout will be used.'
| def set(self, key, value, timeout=None):
| raise NotImplementedError
|
'Delete a key from the cache, failing silently.'
| def delete(self, key):
| raise NotImplementedError
|
'Fetch a bunch of keys from the cache. For certain backends (memcached,
pgsql) this can be *much* faster when fetching multiple values.
Returns a dict mapping each key in keys to its value. If the given
key is missing, it will be missing from the response dict.'
| def get_many(self, keys):
| d = {}
for k in keys:
val = self.get(k)
if (val is not None):
d[k] = val
return d
|
'Returns True if the key is in the cache and has not expired.'
| def has_key(self, key):
| return (self.get(key) is not None)
|
'ValidationError can be passed a string or a list.'
| def __init__(self, message):
| if isinstance(message, list):
self.messages = message
else:
assert isinstance(message, (basestring, Promise)), ('%s should be a string' % repr(message))
self.messages = [message]
|
'ValidationError can be passed a string or a list.'
| def __init__(self, message):
| if isinstance(message, list):
self.messages = message
else:
assert isinstance(message, (basestring, Promise)), ("'%s' should be a string" % message)
self.messages = [message]
|
'Create new instance or return current instance
Basically this method of construction allows us to
short-circuit creation of references to already-
referenced instance methods. The key corresponding
to the target is calculated, and if there is already
an existing reference, that is returned, with its
deletionMethods a... | def __new__(cls, target, onDelete=None, *arguments, **named):
| key = cls.calculateKey(target)
current = cls._allInstances.get(key)
if (current is not None):
current.deletionMethods.append(onDelete)
return current
else:
base = super(BoundMethodWeakref, cls).__new__(cls)
cls._allInstances[key] = base
base.__init__(target, onDel... |
'Return a weak-reference-like instance for a bound method
target -- the instance-method target for the weak
reference, must have im_self and im_func attributes
and be reconstructable via:
target.im_func.__get__( target.im_self )
which is true of built-in instance methods.
onDelete -- optional callback which will be cal... | def __init__(self, target, onDelete=None):
| def remove(weak, self=self):
'Set self.isDead to true when method or instance is destroyed'
methods = self.deletionMethods[:]
del self.deletionMethods[:]
try:
del self.__class__._allInstances[self.key]
except KeyError:
pass
... |
'Calculate the reference key for this reference
Currently this is a two-tuple of the id()\'s of the
target object and the target function respectively.'
| def calculateKey(cls, target):
| return (id(target.im_self), id(target.im_func))
|
'Give a friendly representation of the object'
| def __str__(self):
| return ('%s( %s.%s )' % (self.__class__.__name__, self.selfName, self.funcName))
|
'Whether we are still a valid reference'
| def __nonzero__(self):
| return (self() is not None)
|
'Compare with another reference'
| def __cmp__(self, other):
| if (not isinstance(other, self.__class__)):
return cmp(self.__class__, type(other))
return cmp(self.key, other.key)
|
'Return a strong reference to the bound method
If the target cannot be retrieved, then will
return None, otherwise returns a bound instance
method for our object and function.
Note:
You may call this method any number of times,
as it does not invalidate the reference.'
| def __call__(self):
| target = self.weakSelf()
if (target is not None):
function = self.weakFunc()
if (function is not None):
return function.__get__(target)
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.