desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Ensure that next_element and previous_element are properly
set for all descendants of the given element.'
| def assertConnectedness(self, element):
| earlier = None
for e in element.descendants:
if earlier:
self.assertEqual(e, earlier.next_element)
self.assertEqual(earlier, e.previous_element)
earlier = e
|
'Assert that a given doctype string is handled correctly.'
| def assertDoctypeHandled(self, doctype_fragment):
| (doctype_str, soup) = self._document_with_doctype(doctype_fragment)
doctype = soup.contents[0]
self.assertEqual(doctype.__class__, Doctype)
self.assertEqual(doctype, doctype_fragment)
self.assertEqual(str(soup)[:len(doctype_str)], doctype_str)
self.assertEqual(soup.p.contents[0], 'foo')
|
'Generate and parse a document with the given doctype.'
| def _document_with_doctype(self, doctype_fragment):
| doctype = ('<!DOCTYPE %s>' % doctype_fragment)
markup = (doctype + '\n<p>foo</p>')
soup = self.soup(markup)
return (doctype, soup)
|
'Make sure normal, everyday HTML doctypes are handled correctly.'
| def test_normal_doctypes(self):
| self.assertDoctypeHandled('html')
self.assertDoctypeHandled('html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"')
|
'A real XHTML document should come out more or less the same as it went in.'
| def test_real_xhtml_document(self):
| markup = '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head><title>Hello.</title></head>\n<body>Goodbye.</body>\n</html>'
soup = self.soup(markup)
self.assertEqual(soup.encode... |
'Make sure you can copy the tree builder.
This is important because the builder is part of a
BeautifulSoup object, and we want to be able to copy that.'
| def test_deepcopy(self):
| copy.deepcopy(self.default_builder)
|
'A <p> tag is never designated as an empty-element tag.
Even if the markup shows it as an empty-element tag, it
shouldn\'t be presented that way.'
| def test_p_tag_is_never_empty_element(self):
| soup = self.soup('<p/>')
self.assertFalse(soup.p.is_empty_element)
self.assertEqual(str(soup.p), '<p></p>')
|
'A tag that\'s not closed by the end of the document should be closed.
This applies to all tags except empty-element tags.'
| def test_unclosed_tags_get_closed(self):
| self.assertSoupEquals('<p>', '<p></p>')
self.assertSoupEquals('<b>', '<b></b>')
self.assertSoupEquals('<br>', '<br/>')
|
'A <br> tag is designated as an empty-element tag.
Some parsers treat <br></br> as one <br/> tag, some parsers as
two tags, but it should always be an empty-element tag.'
| def test_br_is_always_empty_element_tag(self):
| soup = self.soup('<br></br>')
self.assertTrue(soup.br.is_empty_element)
self.assertEqual(str(soup.br), '<br/>')
|
'Whitespace must be preserved in <pre> and <textarea> tags,
even if that would mean not prettifying the markup.'
| def test_preserved_whitespace_in_pre_and_textarea(self):
| pre_markup = '<pre> </pre>'
textarea_markup = '<textarea> woo\nwoo </textarea>'
self.assertSoupEquals(pre_markup)
self.assertSoupEquals(textarea_markup)
soup = self.soup(pre_markup)
self.assertEqual(soup.pre.prettify(), pre_markup)
soup = self.soup(textarea_markup)
s... |
'Inline elements can be nested indefinitely.'
| def test_nested_inline_elements(self):
| b_tag = '<b>Inside a B tag</b>'
self.assertSoupEquals(b_tag)
nested_b_tag = '<p>A <i>nested <b>tag</b></i></p>'
self.assertSoupEquals(nested_b_tag)
double_nested_b_tag = '<p>A <a>doubly <i>nested <b>tag</b></i></a></p>'
self.assertSoupEquals(nested_b_tag)
|
'Block elements can be nested.'
| def test_nested_block_level_elements(self):
| soup = self.soup('<blockquote><p><b>Foo</b></p></blockquote>')
blockquote = soup.blockquote
self.assertEqual(blockquote.p.b.string, 'Foo')
self.assertEqual(blockquote.b.string, 'Foo')
|
'One table can go inside another one.'
| def test_correctly_nested_tables(self):
| markup = '<table id="1"><tr><td>Here\'s another table:<table id="2"><tr><td>foo</td></tr></table></td>'
self.assertSoupEquals(markup, '<table id="1"><tr><td>Here\'s another table:<table id="2"><tr><td>foo</td></tr></table></td></tr></table>')
self.assertSoupEquals('<table><thead><tr>... |
'Mostly to prevent a recurrence of a bug in the html5lib treebuilder.'
| def test_multipart_strings(self):
| soup = self.soup('<html><h2>\nfoo</h2><p></p></html>')
self.assertEqual('p', soup.h2.string.next_element.name)
self.assertEqual('p', soup.p.name)
self.assertConnectedness(soup)
|
'Prevent recurrence of a bug in the html5lib treebuilder.'
| def test_head_tag_between_head_and_body(self):
| content = '<html><head></head>\n <link></link>\n <body>foo</body>\n</html>\n'
soup = self.soup(content)
self.assertNotEqual(None, soup.html.body)
self.assertConnectedness(soup)
|
'Prevent recurrence of a bug in the html5lib treebuilder.'
| def test_multiple_copies_of_a_tag(self):
| content = '<!DOCTYPE html>\n<html>\n <body>\n <article id="a" >\n <div><a href="1"></div>\n <footer>\n <a href="2"></a>\n </footer>\n </article>\n </body>\n</html>\n'
soup = self.soup(content)
self.assertConnected... |
'Parsers don\'t need to *understand* namespaces, but at the
very least they should not choke on namespaces or lose
data.'
| def test_basic_namespaces(self):
| markup = '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:mathml="http://www.w3.org/1998/Math/MathML" xmlns:svg="http://www.w3.org/2000/svg"><head></head><body><mathml:msqrt>4</mathml:msqrt><b svg:fill="red"></b></body></html>'
soup = self.soup(markup)
self.assertEqual(markup, soup.encode())
... |
'Parsers should be able to work with SoupStrainers.'
| def test_soupstrainer(self):
| strainer = SoupStrainer('b')
soup = self.soup('A <b>bold</b> <meta/> <i>statement</i>', parse_only=strainer)
self.assertEqual(soup.decode(), '<b>bold</b>')
|
'A real XHTML document should come out *exactly* the same as it went in.'
| def test_real_xhtml_document(self):
| markup = '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head><title>Hello.</title></head>\n<body>Goodbye.</body>\n</html>'
soup = self.soup(markup)
self.assertEqual(soup.encode... |
'A large XML document should come out the same as it went in.'
| def test_large_xml_document(self):
| markup = (('<?xml version="1.0" encoding="utf-8"?>\n<root>' + ('0' * (2 ** 12))) + '</root>')
soup = self.soup(markup)
self.assertEqual(soup.encode('utf-8'), markup)
|
'Used with a regular expression to substitute the
appropriate XML entity for an XML special character.'
| @classmethod
def _substitute_xml_entity(cls, matchobj):
| entity = cls.CHARACTER_TO_XML_ENTITY[matchobj.group(0)]
return ('&%s;' % entity)
|
'Make a value into a quoted XML attribute, possibly escaping it.
Most strings will be quoted using double quotes.
Bob\'s Bar -> "Bob\'s Bar"
If a string contains double quotes, it will be quoted using
single quotes.
Welcome to "my bar" -> \'Welcome to "my bar"\'
If a string contains both single and double quotes, the
d... | @classmethod
def quoted_attribute_value(self, value):
| quote_with = '"'
if ('"' in value):
if ("'" in value):
replace_with = '"'
value = value.replace('"', replace_with)
else:
quote_with = "'"
return ((quote_with + value) + quote_with)
|
'Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign
will become <, the greater-than sign will become >,
and any ampersands will become &. If you want ampersands
that appear to be part of an entity definition to be left
alone, use substitute_xml_con... | @classmethod
def substitute_xml(cls, value, make_quoted_attribute=False):
| value = cls.AMPERSAND_OR_BRACKET.sub(cls._substitute_xml_entity, value)
if make_quoted_attribute:
value = cls.quoted_attribute_value(value)
return value
|
'Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign will
become <, the greater-than sign will become >, and any
ampersands that are not part of an entity defition will
become &.
:param make_quoted_attribute: If True, then the string will be
quoted,... | @classmethod
def substitute_xml_containing_entities(cls, value, make_quoted_attribute=False):
| value = cls.BARE_AMPERSAND_OR_BRACKET.sub(cls._substitute_xml_entity, value)
if make_quoted_attribute:
value = cls.quoted_attribute_value(value)
return value
|
'Replace certain Unicode characters with named HTML entities.
This differs from data.encode(encoding, \'xmlcharrefreplace\')
in that the goal is to make the result more readable (to those
with ASCII displays) rather than to recover from
errors. There\'s absolutely nothing wrong with a UTF-8 string
containg a LATIN SMAL... | @classmethod
def substitute_html(cls, s):
| return cls.CHARACTER_TO_HTML_ENTITY_RE.sub(cls._substitute_html_entity, s)
|
'Yield a number of encodings that might work for this markup.'
| @property
def encodings(self):
| tried = set()
for e in self.override_encodings:
if self._usable(e, tried):
(yield e)
if self._usable(self.sniffed_encoding, tried):
(yield self.sniffed_encoding)
if (self.declared_encoding is None):
self.declared_encoding = self.find_declared_encoding(self.markup, sel... |
'If a byte-order mark is present, strip it and return the encoding it implies.'
| @classmethod
def strip_byte_order_mark(cls, data):
| encoding = None
if isinstance(data, unicode):
return (data, encoding)
if ((len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00')):
encoding = 'utf-16be'
data = data[2:]
elif ((len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00')):
... |
'Given a document, tries to find its declared encoding.
An XML encoding is declared at the beginning of the document.
An HTML encoding is declared in a <meta> tag, hopefully near the
beginning of the document.'
| @classmethod
def find_declared_encoding(cls, markup, is_html=False, search_entire_document=False):
| if search_entire_document:
xml_endpos = html_endpos = len(markup)
else:
xml_endpos = 1024
html_endpos = max(2048, int((len(markup) * 0.05)))
declared_encoding = None
declared_encoding_match = xml_encoding_re.search(markup, endpos=xml_endpos)
if ((not declared_encoding_match) ... |
'Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character.'
| def _sub_ms_char(self, match):
| orig = match.group(1)
if (self.smart_quotes_to == 'ascii'):
sub = self.MS_CHARS_TO_ASCII.get(orig).encode()
else:
sub = self.MS_CHARS.get(orig)
if (type(sub) == tuple):
if (self.smart_quotes_to == 'xml'):
sub = (('&#x'.encode() + sub[1].encode()) + ';'.enc... |
'Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'
| def _to_unicode(self, data, encoding, errors='strict'):
| return unicode(data, encoding, errors)
|
'Fix characters from one encoding embedded in some other encoding.
Currently the only situation supported is Windows-1252 (or its
subset ISO-8859-1), embedded in UTF-8.
The input must be a bytestring. If you\'ve already converted
the document to Unicode, you\'re too late.
The output is a bytestring in which `embedded_e... | @classmethod
def detwingle(cls, in_bytes, main_encoding='utf8', embedded_encoding='windows-1252'):
| if (embedded_encoding.replace('_', '-').lower() not in ('windows-1252', 'windows_1252')):
raise NotImplementedError('Windows-1252 and ISO-8859-1 are the only currently supported embedded encodings.')
if (main_encoding.lower() not in ('utf8', 'utf-8')):
raise NotImpleme... |
'Format the given string using the given formatter.'
| def format_string(self, s, formatter='minimal'):
| if (not callable(formatter)):
formatter = self._formatter_for_name(formatter)
if (formatter is None):
output = s
else:
output = formatter(s)
return output
|
'Is this element part of an XML tree or an HTML tree?
This is used when mapping a formatter name ("minimal") to an
appropriate function (one that performs entity-substitution on
the contents of <script> and <style> tags, or not). It can be
inefficient, but it should be called very rarely.'
| @property
def _is_xml(self):
| if (self.known_xml is not None):
return self.known_xml
if (self.parent is None):
return getattr(self, 'is_xml', False)
return self.parent._is_xml
|
'Look up a formatter function based on its name and the tree.'
| def _formatter_for_name(self, name):
| if self._is_xml:
return self.XML_FORMATTERS.get(name, EntitySubstitution.substitute_xml)
else:
return self.HTML_FORMATTERS.get(name, HTMLAwareEntitySubstitution.substitute_xml)
|
'Sets up the initial relations between this element and
other elements.'
| def setup(self, parent=None, previous_element=None, next_element=None, previous_sibling=None, next_sibling=None):
| self.parent = parent
self.previous_element = previous_element
if (previous_element is not None):
self.previous_element.next_element = self
self.next_element = next_element
if self.next_element:
self.next_element.previous_element = self
self.next_sibling = next_sibling
if self... |
'Destructively rips this element out of the tree.'
| def extract(self):
| if (self.parent is not None):
del self.parent.contents[self.parent.index(self)]
last_child = self._last_descendant()
next_element = last_child.next_element
if ((self.previous_element is not None) and (self.previous_element is not next_element)):
self.previous_element.next_element = next_... |
'Finds the last element beneath this object to be parsed.'
| def _last_descendant(self, is_initialized=True, accept_self=True):
| if (is_initialized and self.next_sibling):
last_child = self.next_sibling.previous_element
else:
last_child = self
while (isinstance(last_child, Tag) and last_child.contents):
last_child = last_child.contents[(-1)]
if ((not accept_self) and (last_child is self)):
... |
'Appends the given tag to the contents of this tag.'
| def append(self, tag):
| self.insert(len(self.contents), tag)
|
'Makes the given element the immediate predecessor of this one.
The two elements will have the same parent, and the given element
will be immediately before this one.'
| def insert_before(self, predecessor):
| if (self is predecessor):
raise ValueError("Can't insert an element before itself.")
parent = self.parent
if (parent is None):
raise ValueError("Element has no parent, so 'before' has no meaning.")
if isinstance(predecessor, PageElement):
pr... |
'Makes the given element the immediate successor of this one.
The two elements will have the same parent, and the given element
will be immediately after this one.'
| def insert_after(self, successor):
| if (self is successor):
raise ValueError("Can't insert an element after itself.")
parent = self.parent
if (parent is None):
raise ValueError("Element has no parent, so 'after' has no meaning.")
if isinstance(successor, PageElement):
successo... |
'Returns the first item that matches the given criteria and
appears after this Tag in the document.'
| def find_next(self, name=None, attrs={}, text=None, **kwargs):
| return self._find_one(self.find_all_next, name, attrs, text, **kwargs)
|
'Returns all items that match the given criteria and appear
after this Tag in the document.'
| def find_all_next(self, name=None, attrs={}, text=None, limit=None, **kwargs):
| return self._find_all(name, attrs, text, limit, self.next_elements, **kwargs)
|
'Returns the closest sibling to this Tag that matches the
given criteria and appears after this Tag in the document.'
| def find_next_sibling(self, name=None, attrs={}, text=None, **kwargs):
| return self._find_one(self.find_next_siblings, name, attrs, text, **kwargs)
|
'Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document.'
| def find_next_siblings(self, name=None, attrs={}, text=None, limit=None, **kwargs):
| return self._find_all(name, attrs, text, limit, self.next_siblings, **kwargs)
|
'Returns the first item that matches the given criteria and
appears before this Tag in the document.'
| def find_previous(self, name=None, attrs={}, text=None, **kwargs):
| return self._find_one(self.find_all_previous, name, attrs, text, **kwargs)
|
'Returns all items that match the given criteria and appear
before this Tag in the document.'
| def find_all_previous(self, name=None, attrs={}, text=None, limit=None, **kwargs):
| return self._find_all(name, attrs, text, limit, self.previous_elements, **kwargs)
|
'Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document.'
| def find_previous_sibling(self, name=None, attrs={}, text=None, **kwargs):
| return self._find_one(self.find_previous_siblings, name, attrs, text, **kwargs)
|
'Returns the siblings of this Tag that match the given
criteria and appear before this Tag in the document.'
| def find_previous_siblings(self, name=None, attrs={}, text=None, limit=None, **kwargs):
| return self._find_all(name, attrs, text, limit, self.previous_siblings, **kwargs)
|
'Returns the closest parent of this Tag that matches the given
criteria.'
| def find_parent(self, name=None, attrs={}, **kwargs):
| r = None
l = self.find_parents(name, attrs, 1, **kwargs)
if l:
r = l[0]
return r
|
'Returns the parents of this Tag that match the given
criteria.'
| def find_parents(self, name=None, attrs={}, limit=None, **kwargs):
| return self._find_all(name, attrs, None, limit, self.parents, **kwargs)
|
'Iterates over a generator looking for things that match.'
| def _find_all(self, name, attrs, text, limit, generator, **kwargs):
| if ((text is None) and ('string' in kwargs)):
text = kwargs['string']
del kwargs['string']
if isinstance(name, SoupStrainer):
strainer = name
else:
strainer = SoupStrainer(name, attrs, text, **kwargs)
if ((text is None) and (not limit) and (not attrs) and (not kwargs)):
... |
'Force an attribute value into a string representation.
A multi-valued attribute will be converted into a
space-separated stirng.'
| def _attr_value_as_string(self, value, default=None):
| value = self.get(value, default)
if (isinstance(value, list) or isinstance(value, tuple)):
value = ' '.join(value)
return value
|
'Create a function that performs a CSS selector operation.
Takes an operator, attribute and optional value. Returns a
function that will return True for elements that match that
combination.'
| def _attribute_checker(self, operator, attribute, value=''):
| if (operator == '='):
return (lambda el: (el._attr_value_as_string(attribute) == value))
elif (operator == '~'):
def _includes_value(element):
attribute_value = element.get(attribute, [])
if (not isinstance(attribute_value, list)):
attribute_value = attrib... |
'Create a new NavigableString.
When unpickling a NavigableString, this method is called with
the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
passed in to the superclass\'s __new__ or the superclass won\'t know
how to handle non-ASCII characters.'
| def __new__(cls, value):
| if isinstance(value, unicode):
u = unicode.__new__(cls, value)
else:
u = unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
u.setup()
return u
|
'A copy of a NavigableString has the same contents and class
as the original, but it is not connected to the parse tree.'
| def __copy__(self):
| return type(self)(self)
|
'text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper.'
| def __getattr__(self, attr):
| if (attr == 'string'):
return self
else:
raise AttributeError(("'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)))
|
'CData strings are passed into the formatter.
But the return value is ignored.'
| def output_ready(self, formatter='minimal'):
| self.format_string(self, formatter)
return ((self.PREFIX + self) + self.SUFFIX)
|
'Basic constructor.'
| def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None, is_xml=None):
| if (parser is None):
self.parser_class = None
else:
self.parser_class = parser.__class__
if (name is None):
raise ValueError("No value provided for new tag's name.")
self.name = name
self.namespace = namespace
self.prefix = prefix
if (builder is not ... |
'A copy of a Tag is a new Tag, unconnected to the parse tree.
Its contents are a copy of the old Tag\'s contents.'
| def __copy__(self):
| clone = type(self)(None, self.builder, self.name, self.namespace, self.nsprefix, self.attrs, is_xml=self._is_xml)
for attr in ('can_be_empty_element', 'hidden'):
setattr(clone, attr, getattr(self, attr))
for child in self.contents:
clone.append(child.__copy__())
return clone
|
'Is this tag an empty-element tag? (aka a self-closing tag)
A tag that has contents is never an empty-element tag.
A tag that has no contents may or may not be an empty-element
tag. It depends on the builder used to create the tag. If the
builder has a designated list of empty-element tags, then only
a tag whose name s... | @property
def is_empty_element(self):
| return ((len(self.contents) == 0) and self.can_be_empty_element)
|
'Convenience property to get the single string within this tag.
:Return: If this tag has a single string child, return value
is that string. If this tag has no children, or more than one
child, return value is None. If this tag has one child tag,
return value is the \'string\' attribute of the child tag,
recursively.'
| @property
def string(self):
| if (len(self.contents) != 1):
return None
child = self.contents[0]
if isinstance(child, NavigableString):
return child
return child.string
|
'Yield all strings of certain classes, possibly stripping them.
By default, yields only NavigableString and CData objects. So
no comments, processing instructions, etc.'
| def _all_strings(self, strip=False, types=(NavigableString, CData)):
| for descendant in self.descendants:
if (((types is None) and (not isinstance(descendant, NavigableString))) or ((types is not None) and (type(descendant) not in types))):
continue
if strip:
descendant = descendant.strip()
if (len(descendant) == 0):
... |
'Get all child strings, concatenated using the given separator.'
| def get_text(self, separator=u'', strip=False, types=(NavigableString, CData)):
| return separator.join([s for s in self._all_strings(strip, types=types)])
|
'Recursively destroys the contents of this tree.'
| def decompose(self):
| self.extract()
i = self
while (i is not None):
next = i.next_element
i.__dict__.clear()
i.contents = []
i = next
|
'Extract all children. If decompose is True, decompose instead.'
| def clear(self, decompose=False):
| if decompose:
for element in self.contents[:]:
if isinstance(element, Tag):
element.decompose()
else:
element.extract()
else:
for element in self.contents[:]:
element.extract()
|
'Find the index of a child by identity, not value. Avoids issues with
tag.contents.index(element) getting the index of equal elements.'
| def index(self, element):
| for (i, child) in enumerate(self.contents):
if (child is element):
return i
raise ValueError('Tag.index: element not in tag')
|
'Returns the value of the \'key\' attribute for the tag, or
the value given for \'default\' if it doesn\'t have that
attribute.'
| def get(self, key, default=None):
| return self.attrs.get(key, default)
|
'tag[key] returns the value of the \'key\' attribute for the tag,
and throws an exception if it\'s not there.'
| def __getitem__(self, key):
| return self.attrs[key]
|
'Iterating over a tag iterates over its contents.'
| def __iter__(self):
| return iter(self.contents)
|
'The length of a tag is the length of its list of contents.'
| def __len__(self):
| return len(self.contents)
|
'A tag is non-None even if it has no contents.'
| def __nonzero__(self):
| return True
|
'Setting tag[key] sets the value of the \'key\' attribute for the
tag.'
| def __setitem__(self, key, value):
| self.attrs[key] = value
|
'Deleting tag[key] deletes all \'key\' attributes for the tag.'
| def __delitem__(self, key):
| self.attrs.pop(key, None)
|
'Calling a tag like a function is the same as calling its
find_all() method. Eg. tag(\'a\') returns a list of all the A tags
found within this tag.'
| def __call__(self, *args, **kwargs):
| return self.find_all(*args, **kwargs)
|
'Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag.'
| def __eq__(self, other):
| if (self is other):
return True
if ((not hasattr(other, 'name')) or (not hasattr(other, 'attrs')) or (not hasattr(other, 'contents')) or (self.name != other.name) or (self.attrs != other.attrs) or (len(self) != len(other))):
return False
for (i, my_child) in enumerate(self.contents):
... |
'Returns true iff this tag is not identical to the other tag,
as defined in __eq__.'
| def __ne__(self, other):
| return (not (self == other))
|
'Renders this tag as a string.'
| def __repr__(self, encoding='unicode-escape'):
| if PY3K:
return self.decode()
else:
return self.encode(encoding)
|
'Should this tag be pretty-printed?'
| def _should_pretty_print(self, indent_level):
| return ((indent_level is not None) and (self.name not in self.preserve_whitespace_tags))
|
'Returns a Unicode representation of this tag and its contents.
:param eventual_encoding: The tag is destined to be
encoded into this encoding. This method is _not_
responsible for performing that encoding. This information
is passed in so that it can be substituted in if the
document contains a <META> tag that mention... | def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):
| if (not callable(formatter)):
formatter = self._formatter_for_name(formatter)
attrs = []
if self.attrs:
for (key, val) in sorted(self.attrs.items()):
if (val is None):
decoded = key
else:
if (isinstance(val, list) or isinstance(val, tup... |
'Renders the contents of this tag as a Unicode string.
:param indent_level: Each line of the rendering will be
indented this many spaces.
:param eventual_encoding: The tag is destined to be
encoded into this encoding. This method is _not_
responsible for performing that encoding. This information
is passed in so that i... | def decode_contents(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):
| if (not callable(formatter)):
formatter = self._formatter_for_name(formatter)
pretty_print = (indent_level is not None)
s = []
for c in self:
text = None
if isinstance(c, NavigableString):
text = c.output_ready(formatter)
elif isinstance(c, Tag):
s... |
'Renders the contents of this tag as a bytestring.
:param indent_level: Each line of the rendering will be
indented this many spaces.
:param eventual_encoding: The bytestring will be in this encoding.
:param formatter: The output formatter responsible for converting
entities to Unicode characters.'
| def encode_contents(self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):
| contents = self.decode_contents(indent_level, encoding, formatter)
return contents.encode(encoding)
|
'Return only the first child of this Tag matching the given
criteria.'
| def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs):
| r = None
l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
|
'Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the \'attrs\' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or no... | def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs):
| generator = self.descendants
if (not recursive):
generator = self.children
return self._find_all(name, attrs, text, limit, generator, **kwargs)
|
'Perform a CSS selection operation on the current element.'
| def select_one(self, selector):
| value = self.select(selector, limit=1)
if value:
return value[0]
return None
|
'Perform a CSS selection operation on the current element.'
| def select(self, selector, _candidate_generator=None, limit=None):
| if (',' in selector):
context = []
for partial_selector in selector.split(','):
partial_selector = partial_selector.strip()
if (partial_selector == ''):
raise ValueError(('Invalid group selection syntax: %s' % selector))
candidates = se... |
'This was kind of misleading because has_key() (attributes)
was different from __in__ (contents). has_key() is gone in
Python 3, anyway.'
| def has_key(self, key):
| warnings.warn(('has_key is deprecated. Use has_attr("%s") instead.' % key))
return self.has_attr(key)
|
'Update the signature of func with the data in self'
| def update(self, func, **kw):
| func.__name__ = self.name
func.__doc__ = getattr(self, 'doc', None)
func.__dict__ = getattr(self, 'dict', {})
func.__defaults__ = getattr(self, 'defaults', ())
func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
func.__annotations__ = getattr(self, 'annotations', None)
try:
f... |
'Make a new function from a given template and update the signature'
| def make(self, src_templ, evaldict=None, addsource=False, **attrs):
| src = (src_templ % vars(self))
evaldict = (evaldict or {})
mo = DEF.match(src)
if (mo is None):
raise SyntaxError(('not a valid function template\n%s' % src))
name = mo.group(1)
names = set(([name] + [arg.strip(' *') for arg in self.shortsignature.split(',')]))
for n i... |
'Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an
attribute __source__ is added to the result. The attributes attrs
are added, if any.'
| @classmethod
def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource=True, **attrs):
| if isinstance(obj, str):
(name, rest) = obj.strip().split('(', 1)
signature = rest[:(-1)]
func = None
else:
name = None
signature = None
func = obj
self = cls(func, name, signature, defaults, doc, module)
ibody = '\n'.join(((' ' + line) for ... |
'Context manager decorator'
| def __call__(self, func):
| return FunctionMaker.create(func, 'with _self_: return _func_(%(shortsignature)s)', dict(_self_=self, _func_=func), __wrapped__=func)
|
'Create working set from list of path entries (default=sys.path)'
| def __init__(self, entries=None):
| self.entries = []
self.entry_keys = {}
self.by_key = {}
self.callbacks = []
if (entries is None):
entries = sys.path
for entry in entries:
self.add_entry(entry)
|
'Add a path item to ``.entries``, finding any distributions on it
``find_distributions(entry, True)`` is used to find distributions
corresponding to the path entry, and they are added. `entry` is
always appended to ``.entries``, even if it is already present.
(This is because ``sys.path`` can contain the same value mo... | def add_entry(self, entry):
| self.entry_keys.setdefault(entry, [])
self.entries.append(entry)
for dist in find_distributions(entry, True):
self.add(dist, entry, False)
|
'True if `dist` is the active distribution for its project'
| def __contains__(self, dist):
| return (self.by_key.get(dist.key) == dist)
|
'Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is rais... | def find(self, req):
| dist = self.by_key.get(req.key)
if ((dist is not None) and (dist not in req)):
raise VersionConflict(dist, req)
else:
return dist
|
'Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order).'
| def iter_entry_points(self, group, name=None):
| for dist in self:
entries = dist.get_entry_map(group)
if (name is None):
for ep in entries.values():
(yield ep)
elif (name in entries):
(yield entries[name])
|
'Locate distribution for `requires` and run `script_name` script'
| def run_script(self, requires, script_name):
| ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
self.require(requires)[0].run_script(script_name, ns)
|
'Yield distributions for non-duplicate projects in the working set
The yield order is the order in which the items\' path entries were
added to the working set.'
| def __iter__(self):
| seen = {}
for item in self.entries:
for key in self.entry_keys[item]:
if (key not in seen):
seen[key] = 1
(yield self.by_key[key])
|
'Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set\'s ``.entries`` (if it wasn\'t already present).
`dist` is only added to the working set if it\'s for a project that
doesn\... | def add(self, dist, entry=None, insert=True):
| if insert:
dist.insert_on(self.entries, entry)
if (entry is None):
entry = dist.location
keys = self.entry_keys.setdefault(entry, [])
keys2 = self.entry_keys.setdefault(dist.location, [])
if (dist.key in self.by_key):
return
self.by_key[dist.key] = dist
if (dist.key n... |
'List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
not supplied, it defaults to all distributions available within any
entry or distribution in the working set. `installer`, if... | def resolve(self, requirements, env=None, installer=None):
| requirements = list(requirements)[::(-1)]
processed = {}
best = {}
to_activate = []
while requirements:
req = requirements.pop(0)
if (req in processed):
continue
dist = best.get(req.key)
if (dist is None):
dist = self.by_key.get(req.key)
... |
'Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
map(working_set.add, distributions) # add plugins+libs to sys.path
print "Couldn\'t load", errors # display errors
The `plugin_env` should be an ``Environment`` insta... | def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True):
| plugin_projects = list(plugin_env)
plugin_projects.sort()
error_info = {}
distributions = {}
if (full_env is None):
env = Environment(self.entries)
env += plugin_env
else:
env = (full_env + plugin_env)
shadow_set = self.__class__([])
map(shadow_set.add, self)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.