desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Sends one or more EmailMessage objects and returns the number of email
messages sent.'
| def send_messages(self, email_messages):
| raise NotImplementedError
|
'Write all messages to the stream in a thread-safe way.'
| def send_messages(self, email_messages):
| if (not email_messages):
return
self._lock.acquire()
try:
stream_created = self.open()
for message in email_messages:
self.stream.write(('%s\n' % message.message().as_string()))
self.stream.write(('-' * 79))
self.stream.write('\n')
self... |
'Return a unique file name.'
| def _get_filename(self):
| if (self._fname is None):
timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
fname = ('%s-%s.log' % (timestamp, abs(id(self))))
self._fname = os.path.join(self.file_path, fname)
return self._fname
|
'Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).'
| def open(self):
| if self.connection:
return False
try:
self.connection = smtplib.SMTP(self.host, self.port, local_hostname=DNS_NAME.get_fqdn())
if self.use_tls:
self.connection.ehlo()
self.connection.starttls()
self.connection.ehlo()
if (self.username and self.... |
'Closes the connection to the email server.'
| def close(self):
| try:
self.connection.quit()
except socket.sslerror:
self.connection.close()
except:
if self.fail_silently:
return
raise
finally:
self.connection = None
|
'Sends one or more EmailMessage objects and returns the number of email
messages sent.'
| def send_messages(self, email_messages):
| if (not email_messages):
return
self._lock.acquire()
try:
new_conn_created = self.open()
if (not self.connection):
return
num_sent = 0
for message in email_messages:
sent = self._send(message)
if sent:
num_sent += 1
... |
'A helper method that does the actual sending.'
| def _send(self, email_message):
| if (not email_message.recipients()):
return False
from_email = sanitize_address(email_message.from_email, email_message.encoding)
recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.recipients()]
try:
self.connection.sendmail(from_email, recipients, ema... |
'Redirect messages to the dummy outbox'
| def send_messages(self, messages):
| mail.outbox.extend(messages)
return len(messages)
|
'Return the entire formatted message as a string.
Optional `unixfrom\' when True, means include the Unix From_ envelope
header.
This overrides the default as_string() implementation to not mangle
lines that begin with \'From \'. See bug #13433 for details.'
| def as_string(self, unixfrom=False):
| fp = StringIO()
g = Generator(fp, mangle_from_=False)
g.flatten(self, unixfrom=unixfrom)
return fp.getvalue()
|
'Return the entire formatted message as a string.
Optional `unixfrom\' when True, means include the Unix From_ envelope
header.
This overrides the default as_string() implementation to not mangle
lines that begin with \'From \'. See bug #13433 for details.'
| def as_string(self, unixfrom=False):
| fp = StringIO()
g = Generator(fp, mangle_from_=False)
g.flatten(self, unixfrom=unixfrom)
return fp.getvalue()
|
'Initialize a single email message (which can be sent to multiple
recipients).
All strings used to create the message can be unicode strings
(or UTF-8 bytestrings). The SafeMIMEText class will handle any
necessary encoding conversions.'
| def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, cc=None):
| if to:
assert (not isinstance(to, basestring)), '"to" argument must be a list or tuple'
self.to = list(to)
else:
self.to = []
if cc:
assert (not isinstance(cc, basestring)), '"cc" argument must be a list or tuple'
self.cc = li... |
'Returns a list of all recipients of the email (includes direct
addressees as well as Cc and Bcc entries).'
| def recipients(self):
| return ((self.to + self.cc) + self.bcc)
|
'Sends the email message.'
| def send(self, fail_silently=False):
| if (not self.recipients()):
return 0
return self.get_connection(fail_silently).send_messages([self])
|
'Attaches a file with the given filename and content. The filename can
be omitted and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass it is inserted directly
into the resulting message attachments.'
| def attach(self, filename=None, content=None, mimetype=None):
| if isinstance(filename, MIMEBase):
assert (content == mimetype == None)
self.attachments.append(filename)
else:
assert (content is not None)
self.attachments.append((filename, content, mimetype))
|
'Attaches a file from the filesystem.'
| def attach_file(self, path, mimetype=None):
| filename = os.path.basename(path)
content = open(path, 'rb').read()
self.attach(filename, content, mimetype)
|
'Converts the content, mimetype pair into a MIME attachment object.'
| def _create_mime_attachment(self, content, mimetype):
| (basetype, subtype) = mimetype.split('/', 1)
if (basetype == 'text'):
encoding = (self.encoding or settings.DEFAULT_CHARSET)
attachment = SafeMIMEText(smart_str(content, encoding), subtype, encoding)
else:
attachment = MIMEBase(basetype, subtype)
attachment.set_payload(conten... |
'Converts the filename, content, mimetype triple into a MIME attachment
object.'
| def _create_attachment(self, filename, content, mimetype=None):
| if (mimetype is None):
(mimetype, _) = mimetypes.guess_type(filename)
if (mimetype is None):
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
attachment = self._create_mime_attachment(content, mimetype)
if filename:
attachment.add_header('Content-Disposition', 'attachment', filena... |
'Initialize a single email message (which can be sent to multiple
recipients).
All strings used to create the message can be unicode strings (or UTF-8
bytestrings). The SafeMIMEText class will handle any necessary encoding
conversions.'
| def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, alternatives=None, cc=None):
| super(EmailMultiAlternatives, self).__init__(subject, body, from_email, to, bcc, connection, attachments, headers, cc)
self.alternatives = (alternatives or [])
|
'Attach an alternative content representation.'
| def attach_alternative(self, content, mimetype):
| assert (content is not None)
assert (mimetype is not None)
self.alternatives.append((content, mimetype))
|
'Returns the full path of this file.'
| def temporary_file_path(self):
| return self.file.name
|
'Creates a SimpleUploadedFile object from
a dictionary object with the following keys:
- filename
- content-type
- content'
| def from_dict(cls, file_dict):
| return cls(file_dict['filename'], file_dict['content'], file_dict.get('content-type', 'text/plain'))
|
'Read the file and yield chucks of ``chunk_size`` bytes (defaults to
``UploadedFile.DEFAULT_CHUNK_SIZE``).'
| def chunks(self, chunk_size=None):
| if (not chunk_size):
chunk_size = self.DEFAULT_CHUNK_SIZE
if hasattr(self, 'seek'):
self.seek(0)
counter = self.size
while (counter > 0):
(yield self.read(chunk_size))
counter -= chunk_size
|
'Returns ``True`` if you can expect multiple chunks.
NB: If a particular file representation is in memory, subclasses should
always return ``False`` -- there\'s no good reason to read from memory in
chunks.'
| def multiple_chunks(self, chunk_size=None):
| if (not chunk_size):
chunk_size = self.DEFAULT_CHUNK_SIZE
return (self.size > chunk_size)
|
'If ``connection_reset`` is ``True``, Django knows will halt the upload
without consuming the rest of the upload. This will cause the browser to
show a "connection reset" error.'
| def __init__(self, connection_reset=False):
| self.connection_reset = connection_reset
|
'Handle the raw input from the client.
Parameters:
:input_data:
An object that supports reading via .read().
:META:
``request.META``.
:content_length:
The (integer) value of the Content-Length header from the
client.
:boundary: The boundary from the Content-Type header. Be sure to
prepend two \'--\'.'
| def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
| pass
|
'Signal that a new file has been started.
Warning: As with any data from the client, you should not trust
content_length (and sometimes won\'t even get it).'
| def new_file(self, field_name, file_name, content_type, content_length, charset=None):
| self.field_name = field_name
self.file_name = file_name
self.content_type = content_type
self.content_length = content_length
self.charset = charset
|
'Receive data from the streamed upload parser. ``start`` is the position
in the file of the chunk.'
| def receive_data_chunk(self, raw_data, start):
| raise NotImplementedError()
|
'Signal that a file has completed. File size corresponds to the actual
size accumulated by all the chunks.
Subclasses should return a valid ``UploadedFile`` object.'
| def file_complete(self, file_size):
| raise NotImplementedError()
|
'Signal that the upload is complete. Subclasses should perform cleanup
that is necessary for this handler.'
| def upload_complete(self):
| pass
|
'Create the file object to append to as data is coming in.'
| def new_file(self, file_name, *args, **kwargs):
| super(TemporaryFileUploadHandler, self).new_file(file_name, *args, **kwargs)
self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset)
|
'Use the content_length to signal whether or not this handler should be in use.'
| def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
| if (content_length > settings.FILE_UPLOAD_MAX_MEMORY_SIZE):
self.activated = False
else:
self.activated = True
|
'Add the data to the StringIO file.'
| def receive_data_chunk(self, raw_data, start):
| if self.activated:
self.file.write(raw_data)
else:
return raw_data
|
'Return a file object if we\'re activated.'
| def file_complete(self, file_size):
| if (not self.activated):
return
self.file.seek(0)
return InMemoryUploadedFile(file=self.file, field_name=self.field_name, name=self.file_name, content_type=self.content_type, size=file_size, charset=self.charset)
|
'Retrieves the specified file from storage, using the optional mixin
class to customize what features are available on the File returned.'
| def open(self, name, mode='rb', mixin=None):
| file = self._open(name, mode)
if mixin:
file.__class__ = type(mixin.__name__, (mixin, file.__class__), {})
return file
|
'Saves new content to the file specified by name. The content should be a
proper File object, ready to be read from the beginning.'
| def save(self, name, content):
| if (name is None):
name = content.name
name = self.get_available_name(name)
name = self._save(name, content)
return force_unicode(name.replace('\\', '/'))
|
'Returns a filename, based on the provided filename, that\'s suitable for
use in the target storage system.'
| def get_valid_name(self, name):
| return get_valid_filename(name)
|
'Returns a filename that\'s free on the target storage system, and
available for new content to be written to.'
| def get_available_name(self, name):
| (dir_name, file_name) = os.path.split(name)
(file_root, file_ext) = os.path.splitext(file_name)
count = itertools.count(1)
while self.exists(name):
name = os.path.join(dir_name, ('%s_%s%s' % (file_root, count.next(), file_ext)))
return name
|
'Returns a local filesystem path where the file can be retrieved using
Python\'s built-in open() function. Storage systems that can\'t be
accessed using open() should *not* implement this method.'
| def path(self, name):
| raise NotImplementedError("This backend doesn't support absolute paths.")
|
'Deletes the specified file from the storage system.'
| def delete(self, name):
| raise NotImplementedError()
|
'Returns True if a file referened by the given name already exists in the
storage system, or False if the name is available for a new file.'
| def exists(self, name):
| raise NotImplementedError()
|
'Lists the contents of the specified path, returning a 2-tuple of lists;
the first item being directories, the second item being files.'
| def listdir(self, path):
| raise NotImplementedError()
|
'Returns the total size, in bytes, of the file specified by name.'
| def size(self, name):
| raise NotImplementedError()
|
'Returns an absolute URL where the file\'s contents can be accessed
directly by a Web browser.'
| def url(self, name):
| raise NotImplementedError()
|
'Returns the last accessed time (as datetime object) of the file
specified by name.'
| def accessed_time(self, name):
| raise NotImplementedError()
|
'Returns the creation time (as datetime object) of the file
specified by name.'
| def created_time(self, name):
| raise NotImplementedError()
|
'Returns the last modified time (as datetime object) of the file
specified by name.'
| def modified_time(self, name):
| raise NotImplementedError()
|
'Adds the prefix string to a string-based callback.'
| def add_prefix(self, prefix):
| if ((not prefix) or (not hasattr(self, '_callback_str'))):
return
self._callback_str = ((prefix + '.') + self._callback_str)
|
'Validates the given 1-based page number.'
| def validate_number(self, number):
| try:
number = int(number)
except ValueError:
raise PageNotAnInteger('That page number is not an integer')
if (number < 1):
raise EmptyPage('That page number is less than 1')
if (number > self.num_pages):
if ((number == 1) and self.allow... |
'Returns a Page object for the given 1-based page number.'
| def page(self, number):
| number = self.validate_number(number)
bottom = ((number - 1) * self.per_page)
top = (bottom + self.per_page)
if ((top + self.orphans) >= self.count):
top = self.count
return Page(self.object_list[bottom:top], number, self)
|
'Returns the total number of objects, across all pages.'
| def _get_count(self):
| if (self._count is None):
try:
self._count = self.object_list.count()
except (AttributeError, TypeError):
self._count = len(self.object_list)
return self._count
|
'Returns the total number of pages.'
| def _get_num_pages(self):
| if (self._num_pages is None):
if ((self.count == 0) and (not self.allow_empty_first_page)):
self._num_pages = 0
else:
hits = max(1, (self.count - self.orphans))
self._num_pages = int(ceil((hits / float(self.per_page))))
return self._num_pages
|
'Returns a 1-based range of pages for iterating through within
a template for loop.'
| def _get_page_range(self):
| return range(1, (self.num_pages + 1))
|
'Returns the 1-based index of the first object on this page,
relative to total objects in the paginator.'
| def start_index(self):
| if (self.paginator.count == 0):
return 0
return ((self.paginator.per_page * (self.number - 1)) + 1)
|
'Returns the 1-based index of the last object on this page,
relative to total objects found (hits).'
| def end_index(self):
| if (self.number == self.paginator.num_pages):
return self.paginator.count
return (self.number * self.paginator.per_page)
|
'Serialize a queryset.'
| def serialize(self, queryset, **options):
| self.options = options
self.stream = options.pop('stream', StringIO())
self.selected_fields = options.pop('fields', None)
self.use_natural_keys = options.pop('use_natural_keys', False)
self.start_serialization()
for obj in queryset:
self.start_object(obj)
for field in obj._meta.l... |
'Convert a field\'s value to a string.'
| def get_string_value(self, obj, field):
| return smart_unicode(field.value_to_string(obj))
|
'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 (or None if the output stream is
not seekable).'
| def getvalue(self):
| if callable(getattr(self.stream, 'getvalue', None)):
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)
obj_pk = obj._get_pk_val()
if (obj_pk is None):
attrs = {'model': smart_unicode(obj._meta)}
else:
attrs = {'pk':... |
'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):
self.xml.characters(field.value_to_string(obj))
else:
self.xml.addQuickElement('None')
self.xml.endElement('field')
|
'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):
if (self.use_natural_keys and hasattr(related, 'natural_key')):
related = related.natural_key()
for key_value in related:
self.xml.startElement('natural', {})
... |
'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):
| if field.rel.through._meta.auto_created:
self._start_relational_field(field)
if (self.use_natural_keys and hasattr(field.rel.to, 'natural_key')):
def handle_m2m(value):
natural = value.natural_key()
self.xml.startElement('object', {})
for k... |
'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': smart_unicode(field.rel.to._meta)})
|
'Convert an <object> node to a DeserializedObject.'
| def _handle_object(self, node):
| Model = self._get_model_from_node(node, 'model')
if node.hasAttribute('pk'):
pk = node.getAttribute('pk')
else:
pk = None
data = {Model._meta.pk.attname: Model._meta.pk.to_python(pk)}
m2m_data = {}
for field_node in node.getElementsByTagName('field'):
field_name = field_n... |
'Handle a <field> node for a ForeignKey'
| def _handle_fk_field_node(self, node, field):
| if node.getElementsByTagName('None'):
return None
elif hasattr(field.rel.to._default_manager, 'get_by_natural_key'):
keys = node.getElementsByTagName('natural')
if keys:
field_value = [getInnerText(k).strip() for k in keys]
obj = field.rel.to._default_manager.db_m... |
'Handle a <field> node for a ManyToManyField.'
| def _handle_m2m_field_node(self, node, field):
| if hasattr(field.rel.to._default_manager, 'get_by_natural_key'):
def m2m_convert(n):
keys = n.getElementsByTagName('natural')
if keys:
field_value = [getInnerText(k).strip() for k in keys]
obj_pk = field.rel.to._default_manager.db_manager(self.db).get_... |
'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... |
'Constructs the key used by all other methods. By default it
uses the key_func to generate a key (which, by default,
prepends the `key_prefix\' and \'version\'). An different key
function can be provided at the time of cache construction;
alternatively, you can subclass the cache backend to provide
custom key making be... | def make_key(self, key, version=None):
| if (version is None):
version = self.version
new_key = self.key_func(key, self.key_prefix, version)
return new_key
|
'Set a value in the cache if the key does not already exist. If
timeout is given, that timeout will be used for the key; otherwise
the default cache timeout will be used.
Returns True if the value was stored, False otherwise.'
| def add(self, key, value, timeout=None, version=None):
| raise NotImplementedError
|
'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, version=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, version=None):
| raise NotImplementedError
|
'Delete a key from the cache, failing silently.'
| def delete(self, key, version=None):
| 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, version=None):
| d = {}
for k in keys:
val = self.get(k, version=version)
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, version=None):
| return (self.get(key, version=version) is not None)
|
'Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.'
| def incr(self, key, delta=1, version=None):
| value = self.get(key, version=version)
if (value is None):
raise ValueError(("Key '%s' not found" % key))
new_value = (value + delta)
self.set(key, new_value, version=version)
return new_value
|
'Subtract delta from value in the cache. If the key does not exist, raise
a ValueError exception.'
| def decr(self, key, delta=1, version=None):
| return self.incr(key, (- delta), version=version)
|
'Returns True if the key is in the cache and has not expired.'
| def __contains__(self, key):
| return self.has_key(key)
|
'Set a bunch of values in the cache at once from a dict of key/value
pairs. For certain backends (memcached), this is much more efficient
than calling set() multiple times.
If timeout is given, that timeout will be used for the key; otherwise
the default cache timeout will be used.'
| def set_many(self, data, timeout=None, version=None):
| for (key, value) in data.items():
self.set(key, value, timeout=timeout, version=version)
|
'Set a bunch of values in the cache at once. For certain backends
(memcached), this is much more efficient than calling delete() multiple
times.'
| def delete_many(self, keys, version=None):
| for key in keys:
self.delete(key, version=version)
|
'Remove *all* values from the cache at once.'
| def clear(self):
| raise NotImplementedError
|
'Warn about keys that would not be portable to the memcached
backend. This encourages (but does not force) writing backend-portable
cache code.'
| def validate_key(self, key):
| if (len(key) > MEMCACHE_MAX_KEY_LENGTH):
warnings.warn(('Cache key will cause errors if used with memcached: %s (longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH)), CacheKeyWarning)
for char in key:
if ((ord(char) < 33) or (ord(char) == 127)):
warn... |
'Adds delta to the cache version for the supplied key. Returns the
new version.'
| def incr_version(self, key, delta=1, version=None):
| if (version is None):
version = self.version
value = self.get(key, version=version)
if (value is None):
raise ValueError(("Key '%s' not found" % key))
self.set(key, value, version=(version + delta))
self.delete(key, version=version)
return (version + delta)
|
'Substracts delta from the cache version for the supplied key. Returns
the new version.'
| def decr_version(self, key, delta=1, version=None):
| return self.incr_version(key, (- delta), version)
|
'Convert the filename into an md5 string. We\'ll turn the first couple
bits of the path into directory prefixes to be nice to filesystems
that have problems with large numbers of files in a directory.
Thus, a cache key of "foo" gets turnned into a file named
``{cache-dir}ac/bd/18db4cc2f85cedef654fccc4a4d8``.'
| def _key_to_file(self, key):
| path = md5_constructor(key).hexdigest()
path = os.path.join(path[:2], path[2:4], path[4:])
return os.path.join(self._dir, path)
|
'Implements transparent thread-safe access to a memcached client.'
| @property
def _cache(self):
| if (getattr(self, '_client', None) is None):
self._client = self._lib.Client(self._servers)
return self._client
|
'Memcached deals with long (> 30 days) timeouts in a special
way. Call this function to obtain a safe value for your timeout.'
| def _get_memcache_timeout(self, timeout):
| timeout = (timeout or self.default_timeout)
if (timeout > 2592000):
timeout += int(time.time())
return timeout
|
'Validates that the input matches the regular expression.'
| def __call__(self, value):
| if (not self.regex.search(smart_unicode(value))):
raise ValidationError(self.message, code=self.code)
|
'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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.