desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distrib...
def require(self, *requirements):
needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed
'Invoke `callback` for all distributions (including existing ones)'
def subscribe(self, callback):
if (callback in self.callbacks): return self.callbacks.append(callback) for dist in self: callback(dist)
'Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distribu...
def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
self._distmap = {} self._cache = {} self.platform = platform self.python = python self.scan(search_path)
'Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned.'
def can_add(self, dist):
return (((self.python is None) or (dist.py_version is None) or (dist.py_version == self.python)) and compatible_platforms(dist.platform, self.platform))
'Remove `dist` from the environment'
def remove(self, dist):
self._distmap[dist.key].remove(dist)
'Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added.'
def scan(self, search_path=None):
if (search_path is None): search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist)
'Return a newest-to-oldest list of distributions for `project_name`'
def __getitem__(self, project_name):
try: return self._cache[project_name] except KeyError: project_name = project_name.lower() if (project_name not in self._distmap): return [] if (project_name not in self._cache): dists = self._cache[project_name] = self._distmap[project_name] _sort_dists(d...
'Add `dist` if we ``can_add()`` it and it isn\'t already added'
def add(self, dist):
if (self.can_add(dist) and dist.has_version()): dists = self._distmap.setdefault(dist.key, []) if (dist not in dists): dists.append(dist) if (dist.key in self._cache): _sort_dists(self._cache[dist.key])
'Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable ...
def best_match(self, req, working_set, installer=None):
dist = working_set.find(req) if (dist is not None): return dist for dist in self[req.key]: if (dist in req): return dist return self.obtain(req, installer)
'Obtain a distribution matching `requirement` (e.g. via download) Obtain a distro that matches requirement (e.g. via download). In the base ``Environment`` class, this routine just returns ``installer(requirement)``, unless `installer` is None, in which case None is returned instead. This method is a hook that allows...
def obtain(self, requirement, installer=None):
if (installer is not None): return installer(requirement)
'Yield the unique project names of the available distributions'
def __iter__(self):
for key in self._distmap.keys(): if self[key]: (yield key)
'In-place addition of a distribution or environment'
def __iadd__(self, other):
if isinstance(other, Distribution): self.add(other) elif isinstance(other, Environment): for project in other: for dist in other[project]: self.add(dist) else: raise TypeError(("Can't add %r to environment" % (other,))) return self
'Add an environment or distribution to an environment'
def __add__(self, other):
new = self.__class__([], platform=None, python=None) for env in (self, other): new += env return new
'Does the named resource exist?'
def resource_exists(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).has_resource(resource_name)
'Is the named resource an existing directory?'
def resource_isdir(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).resource_isdir(resource_name)
'Return a true filesystem path for specified resource'
def resource_filename(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).get_resource_filename(self, resource_name)
'Return a readable file-like object for specified resource'
def resource_stream(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).get_resource_stream(self, resource_name)
'Return specified resource as a string'
def resource_string(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).get_resource_string(self, resource_name)
'List the contents of the named resource directory'
def resource_listdir(self, package_or_requirement, resource_name):
return get_provider(package_or_requirement).resource_listdir(resource_name)
'Give an error message for problems extracting file(s)'
def extraction_error(self):
old_exc = sys.exc_info()[1] cache_path = (self.extraction_path or get_default_cache()) err = ExtractionError(("Can't extract file(s) to egg cache\n\nThe following error occurred while trying to extract file(s) to the Python egg\ncache:\n\n %s\n\nThe ...
'Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ".egg" extension. `names`, if ...
def get_cache_path(self, archive_name, names=()):
extract_path = (self.extraction_path or get_default_cache()) target_path = os.path.join(extract_path, (archive_name + '-tmp'), *names) try: _bypass_ensure_directory(target_path) except: self.extraction_error() self.cached_files[target_path] = 1 return target_path
'Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don\'t have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are alr...
def postprocess(self, tempname, filename):
if (os.name == 'posix'): mode = ((os.stat(tempname).st_mode | 365) & 4095) os.chmod(tempname, mode)
'Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that ...
def set_extraction_path(self, path):
if self.cached_files: raise ValueError("Can't change extraction path, files already extracted") self.extraction_path = path
'Create a metadata provider from a zipimporter'
def __init__(self, importer):
self.zipinfo = zipimport._zip_directory_cache[importer.archive] self.zip_pre = (importer.archive + os.sep) self.loader = importer if importer.prefix: self.module_path = os.path.join(importer.archive, importer.prefix) else: self.module_path = importer.archive self._setup_prefix()
'Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1,extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional'
def parse(cls, src, dist=None):
try: attrs = extras = () (name, value) = src.split('=', 1) if ('[' in value): (value, extras) = value.split('[', 1) req = Requirement.parse(('x[' + extras)) if req.specs: raise ValueError extras = req.extras if (':' in v...
'Parse an entry point group'
def parse_group(cls, group, lines, dist=None):
if (not MODULE(group)): raise ValueError('Invalid group name', group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if (ep.name in this): raise ValueError('Duplicate entry point', group, ep.name) this[ep.name] = ep return thi...
'Parse a map of entry point groups'
def parse_map(cls, data, dist=None):
if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for (group, lines) in data: if (group is None): if (not lines): continue raise ValueError('Entry points must be listed in groups') ...
'List of Requirements needed for this distro if `extras` are used'
def requires(self, extras=()):
dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra(('%s has no such extra feature %r' % (self, ext))) return deps
'Ensure distribution is importable on `path` (default=sys.path)'
def activate(self, path=None):
if (path is None): path = sys.path self.insert_on(path) if (path is sys.path): fixup_namespace_packages(self.location) map(declare_namespace, self._get_metadata('namespace_packages.txt'))
'Return what this distribution\'s standard .egg filename should be'
def egg_name(self):
filename = ('%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), (self.py_version or PY_MAJOR))) if self.platform: filename += ('-' + self.platform) return filename
'Delegate all unrecognized public attributes to .metadata provider'
def __getattr__(self, attr):
if attr.startswith('_'): raise AttributeError, attr return getattr(self._provider, attr)
'Return a ``Requirement`` that matches this distribution exactly'
def as_requirement(self):
return Requirement.parse(('%s==%s' % (self.project_name, self.version)))
'Return the `name` entry point of `group` or raise ImportError'
def load_entry_point(self, group, name):
ep = self.get_entry_info(group, name) if (ep is None): raise ImportError(('Entry point %r not found' % ((group, name),))) return ep.load()
'Return the entry point map for `group`, or the full entry map'
def get_entry_map(self, group=None):
try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self) if (group is not None): return ep_map.get(group, {}) return ep_map
'Return the EntryPoint object for `group`+`name`, or ``None``'
def get_entry_info(self, group, name):
return self.get_entry_map(group).get(name)
'Insert self.location in path before its nearest parent directory'
def insert_on(self, path, loc=None):
loc = (loc or self.location) if (not loc): return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = [((p and _normalize_cached(p)) or p) for p in path] bp = None for (p, item) in enumerate(npath): if (item == nloc): break elif ((item == bd...
'Copy this distribution, substituting in any changed keyword args'
def clone(self, **kw):
for attr in ('project_name', 'version', 'py_version', 'platform', 'location', 'precedence'): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
'DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'
def __init__(self, project_name, specs, extras):
(self.unsafe_name, project_name) = (project_name, safe_name(project_name)) (self.project_name, self.key) = (project_name, project_name.lower()) index = [(parse_version(v), state_machine[op], op, v) for (op, v) in specs] index.sort() self.specs = [(op, ver) for (parsed, trans, op, ver) in index] ...
'Initialize HTMLSerializer. Keyword options (default given first unless specified) include: inject_meta_charset=True|False Whether it insert a meta element to define the character set of the document. quote_attr_values="legacy"|"spec"|"always" Whether to quote attribute values that don\'t require quoting per legacy bro...
def __init__(self, **kwargs):
unexpected_args = (frozenset(kwargs) - frozenset(self.options)) if (len(unexpected_args) > 0): raise TypeError((u"__init__() got an unexpected keyword argument '%s'" % next(iter(unexpected_args)))) if (u'quote_char' in kwargs): self.use_best_quote_char = False for attr ...
'Node representing an item in the tree. name - The tag name associated with the node parent - The parent of the current node (or None for the document node) value - The value of the current node (applies to text nodes and comments attributes - a dict holding name, value pairs for attributes of the node childNodes - a l...
def __init__(self, name):
self.name = name self.parent = None self.value = None self.attributes = {} self.childNodes = [] self._flags = []
'Insert node as a child of the current node'
def appendChild(self, node):
raise NotImplementedError
'Insert data as text in the current node, positioned before the start of node insertBefore or to the end of the node\'s text.'
def insertText(self, data, insertBefore=None):
raise NotImplementedError
'Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node'
def insertBefore(self, node, refNode):
raise NotImplementedError
'Remove node from the children of the current node'
def removeChild(self, node):
raise NotImplementedError
'Move all the children of the current node to newParent. This is needed so that trees that don\'t store text as nodes move the text in the correct way'
def reparentChildren(self, newParent):
for child in self.childNodes: newParent.appendChild(child) self.childNodes = []
'Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes'
def cloneNode(self):
raise NotImplementedError
'Return true if the node has children or text, false otherwise'
def hasContent(self):
raise NotImplementedError
'Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false'
def elementInActiveFormattingElements(self, name):
for item in self.activeFormattingElements[::(-1)]: if (item == Marker): break elif (item.name == name): return item return False
'Create an element but don\'t insert it anywhere'
def createElement(self, token):
name = token[u'name'] namespace = token.get(u'namespace', self.defaultNamespace) element = self.elementClass(name, namespace) element.attributes = token[u'data'] return element
'Switch the function used to insert an element from the normal one to the misnested table one and back again'
def _setInsertFromTable(self, value):
self._insertFromTable = value if value: self.insertElement = self.insertElementTable else: self.insertElement = self.insertElementNormal
'Create an element and insert it into the tree'
def insertElementTable(self, token):
element = self.createElement(token) if (self.openElements[(-1)].name not in tableInsertModeElements): return self.insertElementNormal(token) else: (parent, insertBefore) = self.getTableMisnestedNodePosition() if (insertBefore is None): parent.appendChild(element) ...
'Insert text data.'
def insertText(self, data, parent=None):
if (parent is None): parent = self.openElements[(-1)] if ((not self.insertFromTable) or (self.insertFromTable and (self.openElements[(-1)].name not in tableInsertModeElements))): parent.insertText(data) else: (parent, insertBefore) = self.getTableMisnestedNodePosition() paren...
'Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node'
def getTableMisnestedNodePosition(self):
lastTable = None fosterParent = None insertBefore = None for elm in self.openElements[::(-1)]: if (elm.name == u'table'): lastTable = elm break if lastTable: if lastTable.parent: fosterParent = lastTable.parent insertBefore = lastTable ...
'Return the final tree'
def getDocument(self):
return self.document
'Return the final fragment'
def getFragment(self):
fragment = self.fragmentClass() self.openElements[0].reparentChildren(fragment) return fragment
'Serialize the subtree of node in the format required by unit tests node - the node from which to start serializing'
def testSerializer(self, node):
raise NotImplementedError
'Create the document root'
def insertRoot(self, token):
docStr = u'' if self.doctype: assert self.doctype.name docStr += (u'<!DOCTYPE %s' % self.doctype.name) if ((self.doctype.publicId is not None) or (self.doctype.systemId is not None)): docStr += (u' PUBLIC "%s" ' % self.infosetFilter.coercePubid((self.doctype.publi...
'This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested.'
def __iter__(self):
self.tokenQueue = deque([]) while self.state(): while self.stream.errors: (yield {u'type': tokenTypes[u'ParseError'], u'data': self.stream.errors.pop(0)}) while self.tokenQueue: (yield self.tokenQueue.popleft())
'This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.'
def consumeNumberEntity(self, isHex):
allowed = digits radix = 10 if isHex: allowed = hexDigits radix = 16 charStack = [] c = self.stream.char() while ((c in allowed) and (c is not EOF)): charStack.append(c) c = self.stream.char() charAsInt = int(u''.join(charStack), radix) if (charAsInt in re...
'This method replaces the need for "entityInAttributeValueState".'
def processEntityInAttribute(self, allowedChar):
self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
'This method is a generic handler for emitting the tags. It also sets the state to "data" because that\'s what\'s needed after a token has been emitted.'
def emitCurrentToken(self):
token = self.currentToken if (token[u'type'] in tagTokenTypes): token[u'name'] = token[u'name'].translate(asciiUpper2Lower) if (token[u'type'] == tokenTypes[u'EndTag']): if token[u'data']: self.tokenQueue.append({u'type': tokenTypes[u'ParseError'], u'data': u'attribut...
'strict - raise an exception when a parse error is encountered tree - a treebuilder class controlling the type of tree that will be returned. Built in treebuilders can be accessed through html5lib.treebuilders.getTreeBuilder(treeType)'
def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False):
self.strict = strict if (tree is None): tree = treebuilders.getTreeBuilder(u'etree') self.tree = tree(namespaceHTMLElements) self.errors = [] self.phases = dict([(name, cls(self, self.tree)) for (name, cls) in getPhases(debug).items()])
'The name of the character encoding that was used to decode the input stream, or :obj:`None` if that is not determined yet.'
@property def documentEncoding(self):
if (not hasattr(self, u'tokenizer')): return None return self.tokenizer.stream.charEncoding[0].name
'Parse a HTML document into a well-formed tree stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) scripting -...
def parse(self, stream, *args, **kwargs):
self._parse(stream, False, None, *args, **kwargs) return self.tree.getDocument()
'Parse a HTML fragment into a well-formed tree fragment container - name of the element we\'re setting the innerHTML property if set to None, default to \'div\' stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specifi...
def parseFragment(self, stream, *args, **kwargs):
self._parse(stream, True, *args, **kwargs) return self.tree.getFragment()
'HTML5 specific normalizations to the token stream'
def normalizeToken(self, token):
if (token[u'type'] == tokenTypes[u'StartTag']): raw = token[u'data'] token[u'data'] = OrderedDict(raw) if (len(raw) > len(token[u'data'])): token[u'data'].update(raw[::(-1)]) return token
'Generic RCDATA/RAWTEXT Parsing algorithm contentType - RCDATA or RAWTEXT'
def parseRCDataRawtext(self, token, contentType):
assert (contentType in (u'RAWTEXT', u'RCDATA')) self.tree.insertElement(token) if (contentType == u'RAWTEXT'): self.tokenizer.state = self.tokenizer.rawtextState else: self.tokenizer.state = self.tokenizer.rcdataState self.originalPhase = self.phase self.phase = self.phases[u'tex...
'Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless ...
def __init__(self, source):
if (not _utils.supports_lone_surrogates): self.reportCharacterErrors = None elif (len(u'\U0010ffff') == 1): self.reportCharacterErrors = self.characterErrorsUCS4 else: self.reportCharacterErrors = self.characterErrorsUCS2 self.newLines = [0] self.charEncoding = (lookupEncodin...
'Produces a file object from source. source can be either a file object, local filename or a string.'
def openStream(self, source):
if hasattr(source, u'read'): stream = source else: stream = StringIO(source) return stream
'Returns (line, col) of the current position in the stream.'
def position(self):
(line, col) = self._position(self.chunkOffset) return ((line + 1), col)
'Read one character from the stream or queue if available. Return EOF when EOF is reached.'
def char(self):
if (self.chunkOffset >= self.chunkSize): if (not self.readChunk()): return EOF chunkOffset = self.chunkOffset char = self.chunk[chunkOffset] self.chunkOffset = (chunkOffset + 1) return char
'Returns a string of characters from the stream up to but not including any character in \'characters\' or EOF. \'characters\' must be a container that supports the \'in\' method and iteration over its characters.'
def charsUntil(self, characters, opposite=False):
try: chars = charsUntilRegEx[(characters, opposite)] except KeyError: if __debug__: for c in characters: assert (ord(c) < 128) regex = u''.join([(u'\\x%02x' % ord(c)) for c in characters]) if (not opposite): regex = (u'^%s' % regex) ...
'Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless ...
def __init__(self, source, override_encoding=None, transport_encoding=None, same_origin_parent_encoding=None, likely_encoding=None, default_encoding=u'windows-1252', useChardet=True):
self.rawStream = self.openStream(source) HTMLUnicodeInputStream.__init__(self, self.rawStream) self.numBytesMeta = 1024 self.numBytesChardet = 100 self.override_encoding = override_encoding self.transport_encoding = transport_encoding self.same_origin_parent_encoding = same_origin_parent_enc...
'Produces a file object from source. source can be either a file object, local filename or a string.'
def openStream(self, source):
if hasattr(source, u'read'): stream = source else: stream = BytesIO(source) try: stream.seek(stream.tell()) except: stream = BufferedStream(stream) return stream
'Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None'
def detectBOM(self):
bomDict = {codecs.BOM_UTF8: u'utf-8', codecs.BOM_UTF16_LE: u'utf-16le', codecs.BOM_UTF16_BE: u'utf-16be', codecs.BOM_UTF32_LE: u'utf-32le', codecs.BOM_UTF32_BE: u'utf-32be'} string = self.rawStream.read(4) assert isinstance(string, bytes) encoding = bomDict.get(string[:3]) seek = 3 if (not encod...
'Report the encoding declared by the meta element'
def detectEncodingMeta(self):
buffer = self.rawStream.read(self.numBytesMeta) assert isinstance(buffer, bytes) parser = EncodingParser(buffer) self.rawStream.seek(0) encoding = parser.getEncoding() if ((encoding is not None) and (encoding.name in (u'utf-16be', u'utf-16le'))): encoding = lookupEncoding(u'utf-8') r...
'Skip past a list of characters'
def skip(self, chars=spaceCharactersBytes):
p = self.position while (p < len(self)): c = self[p:(p + 1)] if (c not in chars): self._position = p return c p += 1 self._position = p return None
'Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone'
def matchBytes(self, bytes):
p = self.position data = self[p:(p + len(bytes))] rv = data.startswith(bytes) if rv: self.position += len(bytes) return rv
'Look for the next sequence of bytes matching a given sequence. If a match is found advance the position to the last byte of the match'
def jumpTo(self, bytes):
newPosition = self[self.position:].find(bytes) if (newPosition > (-1)): if (self._position == (-1)): self._position = 0 self._position += ((newPosition + len(bytes)) - 1) return True else: raise StopIteration
'string - the data to work on for encoding detection'
def __init__(self, data):
self.data = EncodingBytes(data) self.encoding = None
'Skip over comments'
def handleComment(self):
return self.data.jumpTo('-->')
'Return a name,value pair for the next attribute in the stream, if one is found, or None'
def getAttribute(self):
data = self.data c = data.skip((spaceCharactersBytes | frozenset(['/']))) assert ((c is None) or (len(c) == 1)) if (c in ('>', None)): return None attrName = [] attrValue = [] while True: if ((c == '=') and attrName): break elif (c in spaceCharactersBytes)...
'Initialize a Character object. *characterID* -- the unique identifier for the character. *name* -- the name of the Character, if not in the data dictionary. *myName* -- the nickname you use for this character. *myID* -- your personal id for this character. *data* -- a dictionary used to initialize the object. *notes* ...
def _init(self, **kwds):
name = kwds.get('name') if (name and (not self.data.has_key('name'))): self.set_name(name) self.characterID = kwds.get('characterID', None) self.myName = kwds.get('myName', u'')
'Reset the Character object.'
def _reset(self):
self.characterID = None self.myName = u''
'Set the name of the character.'
def set_name(self, name):
try: d = analyze_name(name, canonical=0) self.data.update(d) except: pass
'Valid keys to append to the data.keys() list.'
def _additional_keys(self):
addkeys = [] if self.data.has_key('name'): addkeys += ['long imdb name'] if self.data.has_key('headshot'): addkeys += ['full-size headshot'] return addkeys
'Handle special keys.'
def _getitem(self, key):
if self.data.has_key('name'): if (key == 'long imdb name'): return build_name(self.data) if ((key == 'full-size headshot') and self.data.has_key('headshot')): return self._re_fullsizeURL.sub('', self.data.get('headshot', '')) return None
'Return the characterID.'
def getID(self):
return self.characterID
'The Character is "false" if the self.data does not contain a name.'
def __nonzero__(self):
if self.data.get('name'): return 1 return 0
'Return true if this Character was portrayed in the given Movie or it was impersonated by the given Person.'
def __contains__(self, item):
from Movie import Movie from Person import Person if isinstance(item, Person): for m in flatten(self.data, yieldDictKeys=1, scalar=Movie): if item.isSame(m.currentRole): return 1 elif isinstance(item, Movie): for m in flatten(self.data, yieldDictKeys=1, scalar...
'Return true if two character have the same name and/or characterID.'
def isSameName(self, other):
if (not isinstance(other, self.__class__)): return 0 if (self.data.has_key('name') and other.data.has_key('name') and (build_name(self.data, canonical=0) == build_name(other.data, canonical=0))): return 1 if ((self.accessSystem == other.accessSystem) and (self.characterID is not None) and (s...
'Return a deep copy of a Character instance.'
def __deepcopy__(self, memo):
c = Character(name=u'', characterID=self.characterID, myName=self.myName, myID=self.myID, data=deepcopy(self.data, memo), notes=self.notes, accessSystem=self.accessSystem, titlesRefs=deepcopy(self.titlesRefs, memo), namesRefs=deepcopy(self.namesRefs, memo), charactersRefs=deepcopy(self.charactersRefs, memo)) c....
'String representation of a Character object.'
def __repr__(self):
r = ('<Character id:%s[%s] name:_%s_>' % (self.characterID, self.accessSystem, self.get('name'))) if isinstance(r, unicode): r = r.encode('utf_8', 'replace') return r
'Simply print the short name.'
def __str__(self):
return self.get('name', u'').encode('utf_8', 'replace')
'Simply print the short title.'
def __unicode__(self):
return self.get('name', u'')
'Return a string with a pretty-printed summary for the character.'
def summary(self):
if (not self): return u'' s = (u'Character\n=====\nName: %s\n' % self.get('name', u'')) bio = self.get('biography') if bio: s += (u'Biography: %s\n' % bio[0]) filmo = self.get('filmography') if filmo: a_list = [x.get('long imdb canonical title', u'') for x ...
'Initialize a Movie, Person, Character or Company object. *myID* -- your personal identifier for this object. *data* -- a dictionary used to initialize the object. *notes* -- notes for the person referred in the currentRole attribute; e.g.: \'(voice)\' or the alias used in the movie credits. *accessSystem* -- a string ...
def __init__(self, myID=None, data=None, notes=u'', currentRole=u'', roleID=None, roleIsPerson=False, accessSystem=None, titlesRefs=None, namesRefs=None, charactersRefs=None, modFunct=None, *args, **kwds):
self.reset() self.accessSystem = accessSystem self.myID = myID if (data is None): data = {} self.set_data(data, override=1) self.notes = notes if (titlesRefs is None): titlesRefs = {} self.update_titlesRefs(titlesRefs) if (namesRefs is None): namesRefs = {} ...
'Return the characterID or personID of the currentRole object.'
def _get_roleID(self):
if (not self.__role): return None if isinstance(self.__role, list): return [x.getID() for x in self.__role] return self.currentRole.getID()
'Set the characterID or personID of the currentRole object.'
def _set_roleID(self, roleID):
if (not self.__role): pass if (not self._roleIsPerson): if (not isinstance(roleID, (list, tuple))): self.currentRole.characterID = roleID else: for (index, item) in enumerate(roleID): self.__role[index].characterID = item elif (not isinstance(r...
'Return a Character or Person instance.'
def _get_currentRole(self):
if self.__role: return self.__role return self._roleClass(name=u'', accessSystem=self.accessSystem, modFunct=self.modFunct)