desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Calculates the next value in a sequence where the `FREQ` parameter is specified along with a `BYXXX` parameter at the same "level" (e.g. `HOURLY` specified with `BYHOUR`). :param value: The old value of the component. :param byxxx: The `BYXXX` set, which should have been generated by `rrule._construct_byset`, or somet...
def __mod_distance(self, value, byxxx, base):
accumulator = 0 for ii in range(1, (base + 1)): (div, value) = divmod((value + self._interval), base) accumulator += div if (value in byxxx): return (accumulator, value)
'Include the given :py:class:`rrule` instance in the recurrence set generation.'
@_invalidates_cache def rrule(self, rrule):
self._rrule.append(rrule)
'Include the given :py:class:`datetime` instance in the recurrence set generation.'
@_invalidates_cache def rdate(self, rdate):
self._rdate.append(rdate)
'Include the given rrule instance in the recurrence set exclusion list. Dates which are part of the given recurrence rules will not be generated, even if some inclusive rrule or rdate matches them.'
@_invalidates_cache def exrule(self, exrule):
self._exrule.append(exrule)
'Include the given datetime instance in the recurrence set exclusion list. Dates included that way will not be generated, even if some inclusive rrule or rdate matches them.'
@_invalidates_cache def exdate(self, exdate):
self._exdate.append(exdate)
'Two ways to specify this: +1MO or MO(+1)'
def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs):
l = [] for wday in value.split(','): if ('(' in wday): splt = wday.split('(') w = splt[0] n = int(splt[1][:(-1)]) elif len(wday): for i in range(len(wday)): if (wday[i] not in '+-0123456789'): break n...
'This function breaks the time string into lexical units (tokens), which can be parsed by the parser. Lexical units are demarcated by changes in the character set, so any continuous string of letters is considered one unit, any continuous string of numbers is considered one unit. The main complication arises from the f...
def get_token(self):
if self.tokenstack: return self.tokenstack.pop(0) seenletters = False token = None state = None while (not self.eof): if self.charstack: nextchar = self.charstack.pop(0) else: nextchar = self.instream.read(1) while (nextchar == u'\x00'): ...
'Whether or not the next character is part of a word'
@classmethod def isword(cls, nextchar):
return nextchar.isalpha()
'Whether the next character is part of a number'
@classmethod def isnum(cls, nextchar):
return nextchar.isdigit()
'Whether the next character is whitespace'
@classmethod def isspace(cls, nextchar):
return nextchar.isspace()
'attempt to deduce if a pre 100 year was lost due to padded zeros being taken off'
def find_probable_year_index(self, tokens):
for (index, token) in enumerate(self): potential_year_tokens = _ymd.find_potential_year_tokens(token, tokens) if ((len(potential_year_tokens) == 1) and (len(potential_year_tokens[0]) > 2)): return index
'Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: I...
def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs):
if (default is None): effective_dt = datetime.datetime.now() default = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) else: effective_dt = default (res, skipped_tokens) = self._parse(timestr, **kwargs) if (res is None): raise ValueError(u'Unkno...
'Private method which performs the heavy lifting of parsing, called from ``parse()``, which passes on its ``kwargs`` to this function. :param timestr: The string to parse. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ...
def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, fuzzy_with_tokens=False):
if fuzzy_with_tokens: fuzzy = True info = self.info if (dayfirst is None): dayfirst = info.dayfirst if (yearfirst is None): yearfirst = info.yearfirst res = self._result() l = _timelex.split(timestr) last_skipped_token_i = (-2) skipped_tokens = list() try: ...
'Return a version of this object represented entirely using integer values for the relative attributes. >>> relativedelta(days=1.5, hours=2).normalized() relativedelta(days=1, hours=14) :return: Returns a :class:`dateutil.relativedelta.relativedelta` object.'
def normalized(self):
days = int(self.days) hours_f = round((self.hours + (24 * (self.days - days))), 11) hours = int(hours_f) minutes_f = round((self.minutes + (60 * (hours_f - hours))), 10) minutes = int(minutes_f) seconds_f = round((self.seconds + (60 * (minutes_f - minutes))), 8) seconds = int(seconds_f) ...
'Call with an `rrule` and it will test that `str(rrule)` generates a string which generates the same `rrule` as the input when passed to `rrulestr()`'
def _rrulestr_reverse_test(self, rule):
rr_str = str(rule) rrulestr_rrule = rrulestr(rr_str) self.assertEqual(list(rule), list(rrulestr_rrule))
'When `byhour` is specified with `freq=HOURLY`, there are certain combinations of `dtstart` and `byhour` which result in an rrule with no valid values. See https://github.com/dateutil/dateutil/issues/4'
def testHourlyBadRRule(self):
self.assertRaises(ValueError, rrule, HOURLY, **dict(interval=4, byhour=(7, 11, 15, 19), dtstart=datetime(1997, 9, 2, 9, 0)))
'See :func:`testHourlyBadRRule` for details.'
def testMinutelyBadRRule(self):
self.assertRaises(ValueError, rrule, MINUTELY, **dict(interval=12, byminute=(10, 11, 25, 39, 50), dtstart=datetime(1997, 9, 2, 9, 0)))
'See :func:`testHourlyBadRRule` for details.'
def testSecondlyBadRRule(self):
self.assertRaises(ValueError, rrule, SECONDLY, **dict(interval=10, bysecond=(2, 15, 37, 42, 59), dtstart=datetime(1997, 9, 2, 9, 0)))
'Certain values of :param:`interval` in :class:`rrule`, when combined with certain values of :param:`byhour` create rules which apply to no valid dates. The library should detect this case in the iterator and raise a :exception:`ValueError`.'
def testMinutelyBadComboRRule(self):
def make_bad_rrule(): list(rrule(MINUTELY, interval=120, byhour=(10, 12, 14, 16), count=2, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertRaises(ValueError, make_bad_rrule)
'See :func:`testMinutelyBadComboRRule\' for details.'
def testSecondlyBadComboRRule(self):
def make_bad_minute_rrule(): list(rrule(SECONDLY, interval=360, byminute=(10, 28, 49), count=4, dtstart=datetime(1997, 9, 2, 9, 0))) def make_bad_hour_rrule(): list(rrule(SECONDLY, interval=43200, byhour=(2, 10, 18, 23), count=4, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertRaises(ValueEr...
'See rfc-2445 4.3.10 - This checks for the deprecation warning, and will eventually check for an error.'
def testBadUntilCountRRule(self):
with self.assertWarns(DeprecationWarning): rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0), count=3, until=datetime(1997, 9, 4, 9, 0))
'Load a timezone name from a DLL offset (integer). >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.load_name(112)) \'Eastern Standard Time\' :param offset: A positive integer value referring to a string from the tzres dll. ..note: Offsets found in the registry are generally of the form `@tzres.dll,...
def load_name(self, offset):
resource = self.p_wchar() lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR) nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0) return resource[:nchar]
'Parse strings as returned from the Windows registry into the time zone name as defined in the registry. >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.name_from_string(\'@tzres.dll,-251\')) \'Dateline Daylight Time\' >>> print(tzr.name_from_string(\'Eastern Standard Time\')) \'Eastern Standard Ti...
def name_from_string(self, tzname_str):
if (not tzname_str.startswith('@')): return tzname_str name_splt = tzname_str.split(',-') try: offset = int(name_splt[1]) except: raise ValueError('Malformed timezone string.') return self.load_name(offset)
'Return a list of all time zones known to the system.'
@staticmethod def list():
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) tzkey = winreg.OpenKey(handle, TZKEYNAME) result = [winreg.EnumKey(tzkey, i) for i in range(winreg.QueryInfoKey(tzkey)[0])] tzkey.Close() handle.Close() return result
'Create a FieldArray of <length> fields of class <elements_class>, named "<name>[x]". The **elements_extra_args will be passed to the constructor of each field when yielded.'
def __init__(self, parent, name, elements_class, length, **elements_extra_args):
FieldSet.__init__(self, parent, name) self.array_elements_class = elements_class self.array_length = length self.array_elements_extra_args = elements_extra_args
'Initialize a CPIndex. - target_type is the tuple of expected type for the target CPInfo (if None, then there will be no type check) - target_text_handler is a string transformation function used for pretty printing the target str() result - allow_zero states whether null index is allowed (sometimes, constant pool inde...
def __init__(self, parent, name, description=None, target_types=None, target_text_handler=(lambda x: x), allow_zero=False):
UInt16.__init__(self, parent, name, description) if isinstance(target_types, str): self.target_types = (target_types,) else: self.target_types = target_types self.allow_zero = allow_zero self.target_text_handler = target_text_handler self.getOriginalDisplay = (lambda : self.value...
'Returns the target CPInfo field.'
def get_cp_entry(self):
assert (self.value < self['/constant_pool_count'].value) if (self.allow_zero and (not self.value)): return None cp_entry = self[('/constant_pool/constant_pool[%d]' % self.value)] assert isinstance(cp_entry, CPInfo) if self.target_types: assert (cp_entry.constant_type in self.target_t...
'Returns a human-readable string representation of the constant pool entry. It is used for pretty-printing of the CPIndex fields pointing to it.'
def __str__(self):
if (self.constant_type == 'Utf8'): return self['bytes'].value elif (self.constant_type in ('Integer', 'Float', 'Long', 'Double')): return self['bytes'].display elif (self.constant_type == 'Class'): class_name = str(self['name_index'].get_cp_entry()) return class_name.replace(...
'Number of pages which can really be used for swapping: number of page minus bad pages minus one page (used for the header)'
def getPageCount(self):
return ((self['last_page'].value - self['nb_badpage'].value) - 1)
'@param nb_block: Number of the block concerned'
def __init__(self, parent, name, nb_block):
Bit.__init__(self, parent, name) self.block_nb = self.__class__.block_nb self.__class__.block_nb += 1
'Read integer value (may raise ValueError)'
def createValue(self):
return int(self['value'].value)
'Create an Unicode description'
def createDescription(self):
return self.PARSER_TAGS['description']
'Create MIME type (string), eg. "image/png" If it returns None, "application/octet-stream" is used.'
def createMimeType(self):
if ('mime' in self.PARSER_TAGS): return self.PARSER_TAGS['mime'][0] return None
'Check that the parser is able to parse the stream. Valid results: - True: stream looks valid ; - False: stream is invalid ; - str: string describing the error.'
def validate(self):
raise NotImplementedError()
'Create filename suffix: "." + first value of self.PARSER_TAGS["file_ext"], or None if self.PARSER_TAGS["file_ext"] doesn\'t exist.'
def createFilenameSuffix(self):
file_ext = self.getParserTags().get('file_ext') if isinstance(file_ext, (tuple, list)): file_ext = file_ext[0] return (file_ext and ('.' + file_ext))
'with dxt2_mode on, this field will always use the four color model'
def __init__(self, parent, name, dxt2_mode=False, *args, **kwargs):
FieldSet.__init__(self, parent, name, *args, **kwargs) self.dxt2_mode = dxt2_mode
'File is in EMF format?'
def isEMF(self):
if (1 <= self.current_length): return (self[0].name == 'emf_header') if (self.size < (44 * 8)): return False magic = EMF_Header.MAGIC return (self.stream.readBytes((40 * 8), len(magic)) == magic)
'File is in Aldus Placeable Metafiles format?'
def isAPM(self):
if (1 <= self.current_length): return (self[0].name == 'amf_header') else: magic = PlaceableHeader.MAGIC return (self.stream.readBytes(0, len(magic)) == magic)
'Parse what is left of the block'
def parseBody(self):
size = (self['block_size'].value - (self.current_size // 8)) if (('has_added_size' in self['flags']) and self['flags/has_added_size'].value): size += self['added_size'].value if (size > 0): (yield RawBytes(self, 'body', size, 'Body data'))
'Create modification date as Unicode string, may raise ValueError.'
def getDatetime(self):
timestamp = self.getOctal('mtime') return timestampUNIX(timestamp)
'Read sampling rate. Returns None on error.'
def getSampleRate(self):
version = self['version'].value rate = self['sampling_rate'].value try: return self.SAMPLING_RATES[version][rate] except (KeyError, IndexError): return None
'Read bit rate in bit/sec. Returns None on error.'
def getBitRate(self):
layer = (3 - self['layer'].value) bit_rate = self['bit_rate'].value if (bit_rate in (0, 15)): return None if (self['version'].value == 3): dataset = self.BIT_RATES[1] else: dataset = self.BIT_RATES[2] try: return (dataset[layer][bit_rate] * 1000) except (KeyEr...
'Read frame size in bytes. Returns None on error.'
def getFrameSize(self):
frame_size = self.getBitRate() if (not frame_size): return None sample_rate = self.getSampleRate() if (not sample_rate): return None padding = int(self['use_padding'].value) if (self['layer'].value == self.LAYER_III): if (self['version'].value == self.MPEG_I): ...
'Guess if frames are constant bit rate. If it returns False, you can be sure that frames are variable bit rate. Otherwise, it looks like constant bit rate (on first count fields).'
def looksConstantBitRate(self, count=10):
check_keys = ('version', 'layer', 'bit_rate') last_field = None for (index, field) in enumerate(self.array('frame')): if last_field: for key in check_keys: if (field[key].value != last_field[key].value): return False last_field = field ...
'Get bit rate (number of bit per sample per channel), may returns None if you unable to compute it.'
def getBitsPerSample(self):
return self.BITS_PER_SAMPLE.get(self['codec'].value)
'Display a list of parser with its title * out: output file * title : title of the list to display * format: "rest", "trac", "file-ext", "mime" or "one_line" (default)'
def print_(self, title=None, out=None, verbose=False, format='one-line'):
if (out is None): out = sys.stdout if (format in ('file-ext', 'mime')): extensions = set() for parser in self: file_ext = parser.getParserTags().get(format, ()) file_ext = list(file_ext) try: file_ext.remove('') except Value...
'Load all parsers from "hachoir.parser" module. Return the list of loaded parsers.'
def _load(self):
if self.parser_list: return self.parser_list todo = [] module = __import__('hachoir_parser') for attrname in dir(module): attr = getattr(module, attrname) if isinstance(attr, types.ModuleType): todo.append(attr) for module in todo: for name in dir(module):...
'Add a key (register ?)'
def addkey(self, key):
if (type(key) == str): if (not (key in self._apikey)): self._apikey.append(key) elif (type(key) == list): for k in key: if (not (k in self._apikey)): self._apikey.append(k)
'Removes a key (unregister ?)'
def delkey(self, key):
if (type(key) == str): if (key in self._apikey): self._apikey.remove(key) elif (type(key) == list): for k in key: if (key in self._apikey): self._apikey.remove(k)
'Sets the developer key (and check it has the good length)'
def developerkey(self, developerkey):
if ((type(developerkey) == str) and (len(developerkey) == 48)): self._developerkey = developerkey
'Pushes a message on the registered API keys. takes 5 arguments: - (req) application: application name [256] - (req) event: event name [1000] - (req) description: description [10000] - (opt) url: url [512] - (opt) contenttype: Content Type (act: None (plain text) or text/html) - (o...
def push(self, application='', event='', description='', url='', contenttype=None, priority=0, batch_mode=False, html=False):
datas = {'application': application[:256].encode('utf8'), 'event': event[:1024].encode('utf8'), 'description': description[:10000].encode('utf8'), 'priority': priority} if url: datas['url'] = url[:512] if ((contenttype == 'text/html') or (html == True)): datas['content-type'] = 'text/html' ...
'Convenience function for creating a ready-to-go requests.Session (subclass) object.'
@classmethod def create_scraper(cls, sess=None, **kwargs):
scraper = cls() if sess: attrs = ['auth', 'cert', 'cookies', 'headers', 'hooks', 'params', 'proxies', 'data'] for attr in attrs: val = getattr(sess, attr, None) if val: setattr(scraper, attr, val) return scraper
'Convenience function for building a Cookie HTTP header value.'
@classmethod def get_cookie_string(cls, url, user_agent=None, **kwargs):
(tokens, user_agent) = cls.get_tokens(url, user_agent=user_agent, **kwargs) return ('; '.join(('='.join(pair) for pair in tokens.items())), user_agent)
'Constructor for Number String and Boolean'
def __init__(self, value=None, prototype=None, extensible=False):
self.value = value self.extensible = extensible self.prototype = prototype self.own = {}
'Just like in js: self.prop op= val for example when op is \'+\' it will be self.prop+=val op can be either None for simple assignment or one of:'
def put(self, prop, val, op=None):
if ((self.Class == 'Undefined') or (self.Class == 'Null')): raise MakeError('TypeError', 'Undefiend and null dont have properties!') if (not isinstance(prop, basestring)): prop = prop.to_string().value if (op is not None): val = getattr(self.get(prop), OP_METHODS[op])(...
'Check object coercible'
def cok(self):
if (self.Class in {'Undefined', 'Null'}): raise MakeError('TypeError', "undefined or null can't be converted to object")
'self<other if self_first else other<self. Returns the result of the question: is self smaller than other? in case self_first is false it returns the answer of: is other smaller than self. result is PyJs type: bool or undefined'
def abstract_relational_comparison(self, other, self_first=True):
px = self.to_primitive('Number') py = other.to_primitive('Number') if (not self_first): (px, py) = (py, px) if (not ((px.Class == 'String') and (py.Class == 'String'))): (px, py) = (px.to_number(), py.to_number()) if (px.is_nan() or py.is_nan()): return undefined ...
'returns the result of JS == compare. result is PyJs type: bool'
def abstract_equality_comparison(self, other):
(tx, ty) = (self.TYPE, other.TYPE) if (tx == ty): if ((tx == 'Undefined') or (tx == 'Null')): return true if ((tx == 'Number') or (tx == 'String') or (tx == 'Boolean')): return Js((self.value == other.value)) return Js((self is other)) elif (((tx == 'Undefined...
'checks if self is instance of other'
def instanceof(self, other):
if (not hasattr(other, 'has_instance')): return false return other.has_instance(self)
'Call a property prop as a function (this will be global object). NOTE: dont pass this and arguments here, these will be added automatically!'
def __call__(self, *args):
if (not self.is_callable()): raise MakeError('TypeError', ('%s is not a function' % self.typeof())) return self.call(self.GlobalObject, args)
'Generally not a constructor, raise an error'
def create(self, *args):
raise MakeError('TypeError', ('%s is not a constructor' % self.Class))
'Call a property prop as a method (this will be self). NOTE: dont pass this and arguments here, these will be added automatically!'
def callprop(self, prop, *args):
if (not isinstance(prop, basestring)): prop = prop.to_string().value cand = self.get(prop) if (not cand.is_callable()): raise MakeError('TypeError', ('%s is not a function' % cand.typeof())) return cand.call(self, args)
'returns equivalent python object. for example if this object is javascript array then this method will return equivalent python array'
def to_python(self):
return to_python(self)
'returns equivalent python object. for example if this object is javascript array then this method will return equivalent python array'
def to_py(self):
return self.to_python()
'Doc'
def __init__(self, scope, closure=None):
self.prototype = closure if (closure is None): self.own = {} for (k, v) in six.iteritems(scope): self.define_own_property(k, {'value': v, 'configurable': False, 'writable': False, 'enumerable': False}) else: self.own = scope
'register multiple variables'
def registers(self, lvals):
for lval in lvals: self.register(lval)
'name is py type'
def _set_name(self, name):
if self.own.get('name'): self.func_name = name self.own['name']['value'] = Js(name)
'Calls this function and returns a result (converted to PyJs type so func can return python types) this must be a PyJs object and args must be a python tuple of PyJs objects. arguments object is passed automatically and will be equal to Js(args) (tuple converted to arguments object).You dont need to worry about number ...
def call(self, this, args=()):
if (not hasattr(args, '__iter__')): args = (args,) args = tuple((Js(e) for e in args)) arguments = PyJsArguments(args, self) arglen = self.argcount if (len(args) > arglen): args = args[0:arglen] elif (len(args) < arglen): args += ((undefined,) * (arglen - len(args))) ...
'Constructor for Number String and Boolean'
def __init__(self, value=None, prototype=None):
if (not isinstance(value, basestring)): raise TypeError self.value = value self.prototype = prototype self.own = {} self.own['length'] = {'value': Js(len(value)), 'writable': False, 'enumerable': False, 'configurable': False} if (len(value) == 1): CHAR_BANK[value] = self
'string is of course py string'
def match(self, string, pos):
return self.pat.match(string, pos)
'Perform sctring escape - for regexp literals'
def parsePattern(self):
return {'type': 'Pattern', 'contents': self.parseDisjunction()}
'Perform sctring escape - for regexp literals'
def _interpret_regexp(self, string, flags):
self.index = 0 self.length = len(string) self.source = string self.lineNumber = 0 self.lineStart = 0 octal = False st = u'' inside_square = 0 while (self.index < self.length): template = (u'[%s]' if (not inside_square) else u'%s') ch = self.source[self.index] ...
'performs this operation on a list from *right to left* op must take 2 args a,b,c => op(a, op(b, c))'
def rl(self, lis, op):
it = reversed(lis) res = trans(it.next()) for e in it: e = trans(e) res = op(e, res) return res
'performs this operation on a list from *left to right* op must take 2 args a,b,c => op(op(a, b), c)'
def lr(self, lis, op):
it = iter(lis) res = trans(it.next()) for e in it: e = trans(e) res = op(res, e) return res
'Translates outer operation and calls translate on inner operation. Returns fully translated code.'
def translate(self):
if (not self.code): return '' new = bracket_replace(self.code) cand = new.split(',') if (len(cand) > 1): return self.lr(cand, js_comma) if ('?' in new): cond_ind = new.find('?') tenary_start = 0 for ass in re.finditer(ASSIGNMENT_MATCH, new): cand =...
'executes javascript js in current context During initial execute() the converted js is cached for re-use. That means next time you run the same javascript snippet you save many instructions needed to parse and convert the js code to python code. This cache causes minor overhead (a cache dicts is updated) but the Js=>P...
def execute(self, js=None, use_compilation_plan=False):
try: cache = self.__dict__['cache'] except KeyError: cache = self.__dict__['cache'] = {} hashkey = hashlib.md5(js.encode('utf-8')).digest() try: compiled = cache[hashkey] except KeyError: code = translate_js(js, '', use_compilation_plan=use_compilation_plan) c...
'evaluates expression in current context and returns its value'
def eval(self, expression, use_compilation_plan=False):
code = ('PyJsEvalResult = eval(%s)' % json.dumps(expression)) self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult']
'executes javascript js in current context as opposed to the (faster) self.execute method, you can use your regular debugger to set breakpoints and inspect the generated python code'
def execute_debug(self, js):
code = translate_js(js, '') filename = (((('temp' + os.sep) + '_') + hashlib.md5(code).hexdigest()) + '.py') try: with open(filename, mode='w') as f: f.write(code) execfile(filename, self._context) except Exception as err: raise err finally: os.remove(file...
'evaluates expression in current context and returns its value as opposed to the (faster) self.execute method, you can use your regular debugger to set breakpoints and inspect the generated python code'
def eval_debug(self, expression):
code = ('PyJsEvalResult = eval(%s)' % json.dumps(expression)) self.execute_debug(code) return self['PyJsEvalResult']
'starts to interact (starts interactive console) Something like code.InteractiveConsole'
def console(self):
while True: if six.PY2: code = raw_input('>>> ') else: code = input('>>>') try: print self.eval(code) except KeyboardInterrupt: break except Exception as e: import traceback if DEBUG: s...
'Construct a test DriverManager Test instances are passed a list of extensions to work from rather than loading them from entry points. :param extension: Pre-configured Extension instance :type extension: :class:`~stevedore.extension.Extension` :param namespace: The namespace for the manager; used only for identificati...
@classmethod def make_test_instance(cls, extension, namespace='TESTING', propagate_map_exceptions=False, on_load_failure_callback=None, verify_requirements=False):
o = super(DriverManager, cls).make_test_instance([extension], namespace=namespace, propagate_map_exceptions=propagate_map_exceptions, on_load_failure_callback=on_load_failure_callback, verify_requirements=verify_requirements) return o
'Invokes func() for the single loaded extension. The signature for func() should be:: def func(ext, *args, **kwds): pass The first argument to func(), \'ext\', is the :class:`~stevedore.extension.Extension` instance. Exceptions raised from within func() are logged and ignored. :param func: Callable to invoke for each e...
def __call__(self, func, *args, **kwds):
results = self.map(func, *args, **kwds) if results: return results[0]
'Returns the driver being used by this manager.'
@property def driver(self):
ext = self.extensions[0] return (ext.obj if ext.obj else ext.plugin)
'Format the data and return unicode text. :param data: A dictionary with string keys and simple types as values. :type data: dict(str:?)'
def format(self, data):
for (name, value) in sorted(data.items()): full_text = ': {name} : {value}'.format(name=name, value=value) wrapped_text = textwrap.fill(full_text, initial_indent='', subsequent_indent=' ', width=self.max_width) (yield (wrapped_text + '\n'))
'The module and attribute referenced by this extension\'s entry_point. :return: A string representation of the target of the entry point in \'dotted.module:object\' format.'
@property def entry_point_target(self):
return ('%s:%s' % (self.entry_point.module_name, self.entry_point.attrs[0]))
'Construct a test ExtensionManager Test instances are passed a list of extensions to work from rather than loading them from entry points. :param extensions: Pre-configured Extension instances to use :type extensions: list of :class:`~stevedore.extension.Extension` :param namespace: The namespace for the manager; used ...
@classmethod def make_test_instance(cls, extensions, namespace='TESTING', propagate_map_exceptions=False, on_load_failure_callback=None, verify_requirements=False):
o = cls.__new__(cls) o._init_attributes(namespace, propagate_map_exceptions=propagate_map_exceptions, on_load_failure_callback=on_load_failure_callback) o._init_plugins(extensions) return o
'Returns the names of the discovered extensions'
def names(self):
return [e.name for e in self.extensions]
'Iterate over the extensions invoking func() for each. The signature for func() should be:: def func(ext, *args, **kwds): pass The first argument to func(), \'ext\', is the :class:`~stevedore.extension.Extension` instance. Exceptions raised from within func() are propagated up and processing stopped if self.propagate_m...
def map(self, func, *args, **kwds):
if (not self.extensions): raise NoMatches(('No %s extensions found' % self.namespace)) response = [] for e in self.extensions: self._invoke_one_plugin(response.append, func, e, args, kwds) return response
'Iterate over the extensions invoking a method by name. This is equivalent of using :meth:`map` with func set to `lambda x: x.obj.method_name()` while being more convenient. Exceptions raised from within the called method are propagated up and processing stopped if self.propagate_map_exceptions is True, otherwise they ...
def map_method(self, method_name, *args, **kwds):
return self.map(self._call_extension_method, method_name, *args, **kwds)
'Produce iterator for the manager. Iterating over an ExtensionManager produces the :class:`Extension` instances in the order they would be invoked.'
def __iter__(self):
return iter(self.extensions)
'Return the named extension. Accessing an ExtensionManager as a dictionary (``em[\'name\']``) produces the :class:`Extension` instance with the specified name.'
def __getitem__(self, name):
if (self._extensions_by_name is None): d = {} for e in self.extensions: d[e.name] = e self._extensions_by_name = d return self._extensions_by_name[name]
'Return true if name is in list of enabled extensions.'
def __contains__(self, name):
return any(((extension.name == name) for extension in self.extensions))
'Iterate over the extensions invoking func() for any where filter_func() returns True. The signature of filter_func() should be:: def filter_func(ext, *args, **kwds): pass The first argument to filter_func(), \'ext\', is the :class:`~stevedore.extension.Extension` instance. filter_func() should return True if the exten...
def map(self, filter_func, func, *args, **kwds):
if (not self.extensions): raise NoMatches(('No %s extensions found' % self.namespace)) response = [] for e in self.extensions: if filter_func(e, *args, **kwds): self._invoke_one_plugin(response.append, func, e, args, kwds) return response
'Iterate over the extensions invoking each one\'s object method called `method_name` for any where filter_func() returns True. This is equivalent of using :meth:`map` with func set to `lambda x: x.obj.method_name()` while being more convenient. Exceptions raised from within the called method are propagated up and proce...
def map_method(self, filter_func, method_name, *args, **kwds):
return self.map(filter_func, self._call_extension_method, method_name, *args, **kwds)
'Iterate over the extensions invoking func() for any where the name is in the given list of names. The signature for func() should be:: def func(ext, *args, **kwds): pass The first argument to func(), \'ext\', is the :class:`~stevedore.extension.Extension` instance. Exceptions raised from within func() are propagated u...
def map(self, names, func, *args, **kwds):
response = [] for name in names: try: e = self.by_name[name] except KeyError: LOG.debug('Missing extension %r being ignored', name) else: self._invoke_one_plugin(response.append, func, e, args, kwds) return response
'Iterate over the extensions invoking each one\'s object method called `method_name` for any where the name is in the given list of names. This is equivalent of using :meth:`map` with func set to `lambda x: x.obj.method_name()` while being more convenient. Exceptions raised from within the called method are propagated ...
def map_method(self, names, method_name, *args, **kwds):
return self.map(names, self._call_extension_method, method_name, *args, **kwds)
'Format the data and return unicode text. :param data: A dictionary with string keys and simple types as values. :type data: dict(str:?)'
def format(self, data):
for (name, value) in sorted(data.items()): line = '{name} = {value}\n'.format(name=name, value=value) (yield line)
'Construct a test NamedExtensionManager Test instances are passed a list of extensions to use rather than loading them from entry points. :param extensions: Pre-configured Extension instances :type extensions: list of :class:`~stevedore.extension.Extension` :param namespace: The namespace for the manager; used only for...
@classmethod def make_test_instance(cls, extensions, namespace='TESTING', propagate_map_exceptions=False, on_load_failure_callback=None, verify_requirements=False):
o = cls.__new__(cls) names = [e.name for e in extensions] o._init_attributes(namespace, names, propagate_map_exceptions=propagate_map_exceptions, on_load_failure_callback=on_load_failure_callback) o._init_plugins(extensions) return o
'Return the named extensions. Accessing a HookManager as a dictionary (``em[\'name\']``) produces a list of the :class:`Extension` instance(s) with the specified name, in the order they would be invoked by map().'
def __getitem__(self, name):
if (name != self._name): raise KeyError(name) return self.extensions
'Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming unicode ch...
def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None):
self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent if (separators is not None): (self.item_separator, self.key_separator) = separators if (default is not None): ...