code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
182
url
stringlengths
46
251
license
stringclasses
4 values
def values(self): """ @return: a L{list} of file-contents (values). """ vals = [] keys = self.keys() for key in keys: vals.append(self[key]) return vals
@return: a L{list} of file-contents (values).
values
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def items(self): """ @return: a L{list} of 2-tuples containing key/value pairs. """ items = [] keys = self.keys() for key in keys: items.append((key, self[key])) return items
@return: a L{list} of 2-tuples containing key/value pairs.
items
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def has_key(self, key): """ @type key: bytes @param key: The key to test @return: A true value if this dirdbm has the specified key, a false value otherwise. """ if not type(key) == bytes: raise TypeError("DirDBM key must be bytes") key = self._encode(key) return self._dnamePath.child(key).isfile()
@type key: bytes @param key: The key to test @return: A true value if this dirdbm has the specified key, a false value otherwise.
has_key
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def setdefault(self, key, value): """ @type key: bytes @param key: The key to lookup @param value: The value to associate with key if key is not already associated with a value. """ if key not in self: self[key] = value return value return self[key]
@type key: bytes @param key: The key to lookup @param value: The value to associate with key if key is not already associated with a value.
setdefault
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def get(self, key, default = None): """ @type key: bytes @param key: The key to lookup @param default: The value to return if the given key does not exist @return: The value associated with C{key} or C{default} if not L{DirDBM.has_key(key)} """ if key in self: return self[key] else: return default
@type key: bytes @param key: The key to lookup @param default: The value to return if the given key does not exist @return: The value associated with C{key} or C{default} if not L{DirDBM.has_key(key)}
get
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def __contains__(self, key): """ @see: L{DirDBM.has_key} """ return self.has_key(key)
@see: L{DirDBM.has_key}
__contains__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def update(self, dict): """ Add all the key/value pairs in L{dict} to this dirdbm. Any conflicting keys will be overwritten with the values from L{dict}. @type dict: mapping @param dict: A mapping of key/value pairs to add to this dirdbm. """ for key, val in dict.items(): self[key]=val
Add all the key/value pairs in L{dict} to this dirdbm. Any conflicting keys will be overwritten with the values from L{dict}. @type dict: mapping @param dict: A mapping of key/value pairs to add to this dirdbm.
update
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def copyTo(self, path): """ Copy the contents of this dirdbm to the dirdbm at C{path}. @type path: L{str} @param path: The path of the dirdbm to copy to. If a dirdbm exists at the destination path, it is cleared first. @rtype: C{DirDBM} @return: The dirdbm this dirdbm was copied to. """ path = FilePath(path) assert path != self._dnamePath d = self.__class__(path.path) d.clear() for k in self.keys(): d[k] = self[k] return d
Copy the contents of this dirdbm to the dirdbm at C{path}. @type path: L{str} @param path: The path of the dirdbm to copy to. If a dirdbm exists at the destination path, it is cleared first. @rtype: C{DirDBM} @return: The dirdbm this dirdbm was copied to.
copyTo
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def clear(self): """ Delete all key/value pairs in this dirdbm. """ for k in self.keys(): del self[k]
Delete all key/value pairs in this dirdbm.
clear
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def close(self): """ Close this dbm: no-op, for dbm-style interface compliance. """
Close this dbm: no-op, for dbm-style interface compliance.
close
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def getModificationTime(self, key): """ Returns modification time of an entry. @return: Last modification date (seconds since epoch) of entry C{key} @raise KeyError: Raised when there is no such key """ if not type(key) == bytes: raise TypeError("DirDBM key must be bytes") path = self._dnamePath.child(self._encode(key)) if path.isfile(): return path.getModificationTime() else: raise KeyError(key)
Returns modification time of an entry. @return: Last modification date (seconds since epoch) of entry C{key} @raise KeyError: Raised when there is no such key
getModificationTime
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def __setitem__(self, k, v): """ C{shelf[foo] = bar} Create or modify a textfile in this directory. @type k: str @param k: The key to set @param v: The value to associate with C{key} """ v = pickle.dumps(v) DirDBM.__setitem__(self, k, v)
C{shelf[foo] = bar} Create or modify a textfile in this directory. @type k: str @param k: The key to set @param v: The value to associate with C{key}
__setitem__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def __getitem__(self, k): """ C{dirdbm[foo]} Get and unpickle the contents of a file in this directory. @type k: bytes @param k: The key to lookup @return: The value associated with the given key @raise KeyError: Raised if the given key does not exist """ return pickle.loads(DirDBM.__getitem__(self, k))
C{dirdbm[foo]} Get and unpickle the contents of a file in this directory. @type k: bytes @param k: The key to lookup @return: The value associated with the given key @raise KeyError: Raised if the given key does not exist
__getitem__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def open(file, flag = None, mode = None): """ This is for 'anydbm' compatibility. @param file: The parameter to pass to the DirDBM constructor. @param flag: ignored @param mode: ignored """ return DirDBM(file)
This is for 'anydbm' compatibility. @param file: The parameter to pass to the DirDBM constructor. @param flag: ignored @param mode: ignored
open
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
MIT
def __init__(self, l, containerType): """ @param l: The list of object which may contain some not yet referenced objects. @param containerType: A type of container objects (e.g., C{tuple} or C{set}). """ NotKnown.__init__(self) self.containerType = containerType self.l = l self.locs = list(range(len(l))) for idx in range(len(l)): if not isinstance(l[idx], NotKnown): self.locs.remove(idx) else: l[idx].addDependant(self, idx) if not self.locs: self.resolveDependants(self.containerType(self.l))
@param l: The list of object which may contain some not yet referenced objects. @param containerType: A type of container objects (e.g., C{tuple} or C{set}).
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/crefutil.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/crefutil.py
MIT
def __setitem__(self, n, obj): """ Change the value of one contained objects, and resolve references if all objects have been referenced. """ self.l[n] = obj if not isinstance(obj, NotKnown): self.locs.remove(n) if not self.locs: self.resolveDependants(self.containerType(self.l))
Change the value of one contained objects, and resolve references if all objects have been referenced.
__setitem__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/crefutil.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/crefutil.py
MIT
def __init__(self, l): """ @param l: The list of object which may contain some not yet referenced objects. """ _Container.__init__(self, l, tuple)
@param l: The list of object which may contain some not yet referenced objects.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/crefutil.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/crefutil.py
MIT
def setStyle(style): """Set desired format. @type style: string (one of 'pickle' or 'source') """
Set desired format. @type style: string (one of 'pickle' or 'source')
setStyle
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
MIT
def save(tag=None, filename=None, passphrase=None): """Save object to file. @type tag: string @type filename: string @type passphrase: string """
Save object to file. @type tag: string @type filename: string @type passphrase: string
save
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
MIT
def __init__(self, mainMod): """ @param mainMod: The '__main__' module that this class will proxy. """ self.mainMod = mainMod
@param mainMod: The '__main__' module that this class will proxy.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
MIT
def load(filename, style): """Load an object from a file. Deserialize an object from a file. The file can be encrypted. @param filename: string @param style: string (one of 'pickle' or 'source') """ mode = 'r' if style=='source': from twisted.persisted.aot import unjellyFromSource as _load else: _load, mode = pickle.load, 'rb' fp = open(filename, mode) ee = _EverythingEphemeral(sys.modules['__main__']) sys.modules['__main__'] = ee ee.initRun = 1 with fp: try: value = _load(fp) finally: # restore __main__ if an exception is raised. sys.modules['__main__'] = ee.mainMod styles.doUpgrade() ee.initRun = 0 persistable = IPersistable(value, None) if persistable is not None: persistable.setStyle(style) return value
Load an object from a file. Deserialize an object from a file. The file can be encrypted. @param filename: string @param style: string (one of 'pickle' or 'source')
load
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
MIT
def loadValueFromFile(filename, variable): """Load the value of a variable in a Python file. Run the contents of the file in a namespace and return the result of the variable named C{variable}. @param filename: string @param variable: string """ with open(filename, 'r') as fileObj: data = fileObj.read() d = {'__file__': filename} codeObj = compile(data, filename, "exec") eval(codeObj, d, d) value = d[variable] return value
Load the value of a variable in a Python file. Run the contents of the file in a namespace and return the result of the variable named C{variable}. @param filename: string @param variable: string
loadValueFromFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/sob.py
MIT
def _methodFunction(classObject, methodName): """ Retrieve the function object implementing a method name given the class it's on and a method name. @param classObject: A class to retrieve the method's function from. @type classObject: L{type} or L{types.ClassType} @param methodName: The name of the method whose function to retrieve. @type methodName: native L{str} @return: the function object corresponding to the given method name. @rtype: L{types.FunctionType} """ methodObject = getattr(classObject, methodName) if _PY3: return methodObject return methodObject.im_func
Retrieve the function object implementing a method name given the class it's on and a method name. @param classObject: A class to retrieve the method's function from. @type classObject: L{type} or L{types.ClassType} @param methodName: The name of the method whose function to retrieve. @type methodName: native L{str} @return: the function object corresponding to the given method name. @rtype: L{types.FunctionType}
_methodFunction
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def unpickleMethod(im_name, im_self, im_class): """ Support function for copy_reg to unpickle method refs. @param im_name: The name of the method. @type im_name: native L{str} @param im_self: The instance that the method was present on. @type im_self: L{object} @param im_class: The class where the method was declared. @type im_class: L{types.ClassType} or L{type} or L{None} """ if im_self is None: return getattr(im_class, im_name) try: methodFunction = _methodFunction(im_class, im_name) except AttributeError: log.msg("Method", im_name, "not on class", im_class) assert im_self is not None, "No recourse: no instance to guess from." # Attempt a last-ditch fix before giving up. If classes have changed # around since we pickled this method, we may still be able to get it # by looking on the instance's current class. if im_self.__class__ is im_class: raise return unpickleMethod(im_name, im_self, im_self.__class__) else: if _PY3: maybeClass = () else: maybeClass = tuple([im_class]) bound = types.MethodType(methodFunction, im_self, *maybeClass) return bound
Support function for copy_reg to unpickle method refs. @param im_name: The name of the method. @type im_name: native L{str} @param im_self: The instance that the method was present on. @type im_self: L{object} @param im_class: The class where the method was declared. @type im_class: L{types.ClassType} or L{type} or L{None}
unpickleMethod
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def _pickleFunction(f): """ Reduce, in the sense of L{pickle}'s C{object.__reduce__} special method, a function object into its constituent parts. @param f: The function to reduce. @type f: L{types.FunctionType} @return: a 2-tuple of a reference to L{_unpickleFunction} and a tuple of its arguments, a 1-tuple of the function's fully qualified name. @rtype: 2-tuple of C{callable, native string} """ if f.__name__ == '<lambda>': raise _UniversalPicklingError( "Cannot pickle lambda function: {}".format(f)) return (_unpickleFunction, tuple([".".join([f.__module__, f.__qualname__])]))
Reduce, in the sense of L{pickle}'s C{object.__reduce__} special method, a function object into its constituent parts. @param f: The function to reduce. @type f: L{types.FunctionType} @return: a 2-tuple of a reference to L{_unpickleFunction} and a tuple of its arguments, a 1-tuple of the function's fully qualified name. @rtype: 2-tuple of C{callable, native string}
_pickleFunction
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def _unpickleFunction(fullyQualifiedName): """ Convert a function name into a function by importing it. This is a synonym for L{twisted.python.reflect.namedAny}, but imported locally to avoid circular imports, and also to provide a persistent name that can be stored (and deprecated) independently of C{namedAny}. @param fullyQualifiedName: The fully qualified name of a function. @type fullyQualifiedName: native C{str} @return: A function object imported from the given location. @rtype: L{types.FunctionType} """ from twisted.python.reflect import namedAny return namedAny(fullyQualifiedName)
Convert a function name into a function by importing it. This is a synonym for L{twisted.python.reflect.namedAny}, but imported locally to avoid circular imports, and also to provide a persistent name that can be stored (and deprecated) independently of C{namedAny}. @param fullyQualifiedName: The fully qualified name of a function. @type fullyQualifiedName: native C{str} @return: A function object imported from the given location. @rtype: L{types.FunctionType}
_unpickleFunction
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def pickleStringO(stringo): """ Reduce the given cStringO. This is only called on Python 2, because the cStringIO module only exists on Python 2. @param stringo: The string output to pickle. @type stringo: L{cStringIO.OutputType} """ 'support function for copy_reg to pickle StringIO.OutputTypes' return unpickleStringO, (stringo.getvalue(), stringo.tell())
Reduce the given cStringO. This is only called on Python 2, because the cStringIO module only exists on Python 2. @param stringo: The string output to pickle. @type stringo: L{cStringIO.OutputType}
pickleStringO
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def unpickleStringO(val, sek): """ Convert the output of L{pickleStringO} into an appropriate type for the current python version. This may be called on Python 3 and will convert a cStringIO into an L{io.StringIO}. @param val: The content of the file. @type val: L{bytes} @param sek: The seek position of the file. @type sek: L{int} @return: a file-like object which you can write bytes to. @rtype: L{cStringIO.OutputType} on Python 2, L{io.StringIO} on Python 3. """ x = _cStringIO() x.write(val) x.seek(sek) return x
Convert the output of L{pickleStringO} into an appropriate type for the current python version. This may be called on Python 3 and will convert a cStringIO into an L{io.StringIO}. @param val: The content of the file. @type val: L{bytes} @param sek: The seek position of the file. @type sek: L{int} @return: a file-like object which you can write bytes to. @rtype: L{cStringIO.OutputType} on Python 2, L{io.StringIO} on Python 3.
unpickleStringO
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def pickleStringI(stringi): """ Reduce the given cStringI. This is only called on Python 2, because the cStringIO module only exists on Python 2. @param stringi: The string input to pickle. @type stringi: L{cStringIO.InputType} @return: a 2-tuple of (C{unpickleStringI}, (bytes, pointer)) @rtype: 2-tuple of (function, (bytes, int)) """ return unpickleStringI, (stringi.getvalue(), stringi.tell())
Reduce the given cStringI. This is only called on Python 2, because the cStringIO module only exists on Python 2. @param stringi: The string input to pickle. @type stringi: L{cStringIO.InputType} @return: a 2-tuple of (C{unpickleStringI}, (bytes, pointer)) @rtype: 2-tuple of (function, (bytes, int))
pickleStringI
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def unpickleStringI(val, sek): """ Convert the output of L{pickleStringI} into an appropriate type for the current Python version. This may be called on Python 3 and will convert a cStringIO into an L{io.StringIO}. @param val: The content of the file. @type val: L{bytes} @param sek: The seek position of the file. @type sek: L{int} @return: a file-like object which you can read bytes from. @rtype: L{cStringIO.OutputType} on Python 2, L{io.StringIO} on Python 3. """ x = _cStringIO(val) x.seek(sek) return x
Convert the output of L{pickleStringI} into an appropriate type for the current Python version. This may be called on Python 3 and will convert a cStringIO into an L{io.StringIO}. @param val: The content of the file. @type val: L{bytes} @param sek: The seek position of the file. @type sek: L{int} @return: a file-like object which you can read bytes from. @rtype: L{cStringIO.OutputType} on Python 2, L{io.StringIO} on Python 3.
unpickleStringI
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def __reduce__(self): """ Serialize any subclass of L{Ephemeral} in a way which replaces it with L{Ephemeral} itself. """ return (Ephemeral, ())
Serialize any subclass of L{Ephemeral} in a way which replaces it with L{Ephemeral} itself.
__reduce__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def requireUpgrade(obj): """Require that a Versioned instance be upgraded completely first. """ objID = id(obj) if objID in versionedsToUpgrade and objID not in upgraded: upgraded[objID] = 1 obj.versionUpgrade() return obj
Require that a Versioned instance be upgraded completely first.
requireUpgrade
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def _aybabtu(c): """ Get all of the parent classes of C{c}, not including C{c} itself, which are strict subclasses of L{Versioned}. @param c: a class @returns: list of classes """ # begin with two classes that should *not* be included in the # final result l = [c, Versioned] for b in inspect.getmro(c): if b not in l and issubclass(b, Versioned): l.append(b) # return all except the unwanted classes return l[2:]
Get all of the parent classes of C{c}, not including C{c} itself, which are strict subclasses of L{Versioned}. @param c: a class @returns: list of classes
_aybabtu
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def __getstate__(self, dict=None): """Get state, adding a version number to it on its way out. """ dct = copy.copy(dict or self.__dict__) bases = _aybabtu(self.__class__) bases.reverse() bases.append(self.__class__) # don't forget me!! for base in bases: if 'persistenceForgets' in base.__dict__: for slot in base.persistenceForgets: if slot in dct: del dct[slot] if 'persistenceVersion' in base.__dict__: dct['%s.persistenceVersion' % reflect.qual(base)] = base.persistenceVersion return dct
Get state, adding a version number to it on its way out.
__getstate__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def versionUpgrade(self): """(internal) Do a version upgrade. """ bases = _aybabtu(self.__class__) # put the bases in order so superclasses' persistenceVersion methods # will be called first. bases.reverse() bases.append(self.__class__) # don't forget me!! # first let's look for old-skool versioned's if "persistenceVersion" in self.__dict__: # Hacky heuristic: if more than one class subclasses Versioned, # we'll assume that the higher version number wins for the older # class, so we'll consider the attribute the version of the older # class. There are obviously possibly times when this will # eventually be an incorrect assumption, but hopefully old-school # persistenceVersion stuff won't make it that far into multiple # classes inheriting from Versioned. pver = self.__dict__['persistenceVersion'] del self.__dict__['persistenceVersion'] highestVersion = 0 highestBase = None for base in bases: if 'persistenceVersion' not in base.__dict__: continue if base.persistenceVersion > highestVersion: highestBase = base highestVersion = base.persistenceVersion if highestBase: self.__dict__['%s.persistenceVersion' % reflect.qual(highestBase)] = pver for base in bases: # ugly hack, but it's what the user expects, really if (Versioned not in base.__bases__ and 'persistenceVersion' not in base.__dict__): continue currentVers = base.persistenceVersion pverName = '%s.persistenceVersion' % reflect.qual(base) persistVers = (self.__dict__.get(pverName) or 0) if persistVers: del self.__dict__[pverName] assert persistVers <= currentVers, "Sorry, can't go backwards in time." while persistVers < currentVers: persistVers = persistVers + 1 method = base.__dict__.get('upgradeToVersion%s' % persistVers, None) if method: log.msg( "Upgrading %s (of %s @ %s) to version %s" % (reflect.qual(base), reflect.qual(self.__class__), id(self), persistVers) ) method(self) else: log.msg( 'Warning: cannot upgrade %s to version %s' % (base, persistVers) )
(internal) Do a version upgrade.
versionUpgrade
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/styles.py
MIT
def sampleFunction(): """ A sample function for pickling. """
A sample function for pickling.
sampleFunction
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
MIT
def raise_UniversalPicklingError(self): """ Raise L{UniversalPicklingError}. """ raise _UniversalPicklingError
Raise L{UniversalPicklingError}.
raise_UniversalPicklingError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
MIT
def test_handledByPickleModule(self): """ Handling L{pickle.PicklingError} handles L{_UniversalPicklingError}. """ self.assertRaises(pickle.PicklingError, self.raise_UniversalPicklingError)
Handling L{pickle.PicklingError} handles L{_UniversalPicklingError}.
test_handledByPickleModule
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
MIT
def test_handledBycPickleModule(self): """ Handling L{cPickle.PicklingError} handles L{_UniversalPicklingError}. """ try: import cPickle except ImportError: raise unittest.SkipTest("cPickle not available.") else: self.assertRaises(cPickle.PicklingError, self.raise_UniversalPicklingError)
Handling L{cPickle.PicklingError} handles L{_UniversalPicklingError}.
test_handledBycPickleModule
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
MIT
def test_instanceBuildingNamePresent(self): """ L{unpickleMethod} returns an instance method bound to the instance passed to it. """ foo = Foo() m = unpickleMethod('method', foo, Foo) self.assertEqual(m, foo.method) self.assertIsNot(m, foo.method)
L{unpickleMethod} returns an instance method bound to the instance passed to it.
test_instanceBuildingNamePresent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
MIT
def test_instanceBuildingNameNotPresent(self): """ If the named method is not present in the class, L{unpickleMethod} finds a method on the class of the instance and returns a bound method from there. """ foo = Foo() m = unpickleMethod('method', foo, Bar) self.assertEqual(m, foo.method) self.assertIsNot(m, foo.method)
If the named method is not present in the class, L{unpickleMethod} finds a method on the class of the instance and returns a bound method from there.
test_instanceBuildingNameNotPresent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
MIT
def test_primeDirective(self): """ We do not contaminate normal function pickling with concerns from Twisted. """ def expected(n): return "\n".join([ "c" + __name__, sampleFunction.__name__, "p" + n, "." ]).encode("ascii") self.assertEqual(pickle.dumps(sampleFunction, protocol=0), expected("0")) try: import cPickle except: pass else: self.assertEqual( cPickle.dumps(sampleFunction, protocol=0), expected("1") )
We do not contaminate normal function pickling with concerns from Twisted.
test_primeDirective
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
MIT
def test_lambdaRaisesPicklingError(self): """ Pickling a C{lambda} function ought to raise a L{pickle.PicklingError}. """ self.assertRaises(pickle.PicklingError, pickle.dumps, lambdaExample) try: import cPickle except: pass else: self.assertRaises(cPickle.PicklingError, cPickle.dumps, lambdaExample)
Pickling a C{lambda} function ought to raise a L{pickle.PicklingError}.
test_lambdaRaisesPicklingError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/test/test_styles.py
MIT
def __init__(self, descriptors): """ @param descriptors: The descriptors which will be returned from calls to C{inheritedDescriptors}. """ self._descriptors = descriptors
@param descriptors: The descriptors which will be returned from calls to C{inheritedDescriptors}.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/systemd.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/systemd.py
MIT
def fromEnvironment(cls, environ=None, start=None): """ @param environ: A dictionary-like object to inspect to discover inherited descriptors. By default, L{None}, indicating that the real process environment should be inspected. The default is suitable for typical usage. @param start: An integer giving the lowest value of an inherited descriptor systemd will give us. By default, L{None}, indicating the known correct (that is, in agreement with systemd) value will be used. The default is suitable for typical usage. @return: A new instance of C{cls} which can be used to look up the descriptors which have been inherited. """ if environ is None: from os import environ if start is None: start = cls._START descriptors = [] try: pid = int(environ['LISTEN_PID']) except (KeyError, ValueError): pass else: if pid == getpid(): try: count = int(environ['LISTEN_FDS']) except (KeyError, ValueError): pass else: descriptors = range(start, start + count) del environ['LISTEN_PID'], environ['LISTEN_FDS'] return cls(descriptors)
@param environ: A dictionary-like object to inspect to discover inherited descriptors. By default, L{None}, indicating that the real process environment should be inspected. The default is suitable for typical usage. @param start: An integer giving the lowest value of an inherited descriptor systemd will give us. By default, L{None}, indicating the known correct (that is, in agreement with systemd) value will be used. The default is suitable for typical usage. @return: A new instance of C{cls} which can be used to look up the descriptors which have been inherited.
fromEnvironment
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/systemd.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/systemd.py
MIT
def inheritedDescriptors(self): """ @return: The configured list of descriptors. """ return list(self._descriptors)
@return: The configured list of descriptors.
inheritedDescriptors
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/systemd.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/systemd.py
MIT
def serialize(self, write, attrs=None, attributeRenderer='toVT102'): """ Serialize the text attribute and its children. @param write: C{callable}, taking one C{str} argument, called to output a single text attribute at a time. @param attrs: A formatting state instance used to determine how to serialize the attribute children. @type attributeRenderer: C{str} @param attributeRenderer: Name of the method on I{attrs} that should be called to render the attributes during serialization. Defaults to C{'toVT102'}. """ if attrs is None: attrs = DefaultFormattingState() for ch in self.children: if isinstance(ch, _Attribute): ch.serialize(write, attrs.copy(), attributeRenderer) else: renderMeth = getattr(attrs, attributeRenderer) write(renderMeth()) write(ch)
Serialize the text attribute and its children. @param write: C{callable}, taking one C{str} argument, called to output a single text attribute at a time. @param attrs: A formatting state instance used to determine how to serialize the attribute children. @type attributeRenderer: C{str} @param attributeRenderer: Name of the method on I{attrs} that should be called to render the attributes during serialization. Defaults to C{'toVT102'}.
serialize
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
MIT
def copy(self): """ Make a copy of this formatting state. @return: A formatting state instance. """ return type(self)()
Make a copy of this formatting state. @return: A formatting state instance.
copy
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
MIT
def _withAttribute(self, name, value): """ Add a character attribute to a copy of this formatting state. @param name: Attribute name to be added to formatting state. @param value: Attribute value. @return: A formatting state instance with the new attribute. """ return self.copy()
Add a character attribute to a copy of this formatting state. @param name: Attribute name to be added to formatting state. @param value: Attribute value. @return: A formatting state instance with the new attribute.
_withAttribute
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
MIT
def toVT102(self): """ Emit a VT102 control sequence that will set up all the attributes this formatting state has set. @return: A string containing VT102 control sequences that mimic this formatting state. """ return ''
Emit a VT102 control sequence that will set up all the attributes this formatting state has set. @return: A string containing VT102 control sequences that mimic this formatting state.
toVT102
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
MIT
def flatten(output, attrs, attributeRenderer='toVT102'): """ Serialize a sequence of characters with attribute information The resulting string can be interpreted by compatible software so that the contained characters are displayed and, for those attributes which are supported by the software, the attributes expressed. The exact result of the serialization depends on the behavior of the method specified by I{attributeRenderer}. For example, if your terminal is VT102 compatible, you might run this for a colorful variation on the \"hello world\" theme:: from twisted.conch.insults.text import flatten, attributes as A from twisted.conch.insults.helper import CharacterAttribute print(flatten( A.normal[A.bold[A.fg.red['He'], A.fg.green['ll'], A.fg.magenta['o'], ' ', A.fg.yellow['Wo'], A.fg.blue['rl'], A.fg.cyan['d!']]], CharacterAttribute())) @param output: Object returned by accessing attributes of the module-level attributes object. @param attrs: A formatting state instance used to determine how to serialize C{output}. @type attributeRenderer: C{str} @param attributeRenderer: Name of the method on I{attrs} that should be called to render the attributes during serialization. Defaults to C{'toVT102'}. @return: A string expressing the text and display attributes specified by L{output}. """ flattened = [] output.serialize(flattened.append, attrs, attributeRenderer) return ''.join(flattened)
Serialize a sequence of characters with attribute information The resulting string can be interpreted by compatible software so that the contained characters are displayed and, for those attributes which are supported by the software, the attributes expressed. The exact result of the serialization depends on the behavior of the method specified by I{attributeRenderer}. For example, if your terminal is VT102 compatible, you might run this for a colorful variation on the \"hello world\" theme:: from twisted.conch.insults.text import flatten, attributes as A from twisted.conch.insults.helper import CharacterAttribute print(flatten( A.normal[A.bold[A.fg.red['He'], A.fg.green['ll'], A.fg.magenta['o'], ' ', A.fg.yellow['Wo'], A.fg.blue['rl'], A.fg.cyan['d!']]], CharacterAttribute())) @param output: Object returned by accessing attributes of the module-level attributes object. @param attrs: A formatting state instance used to determine how to serialize C{output}. @type attributeRenderer: C{str} @param attributeRenderer: Name of the method on I{attrs} that should be called to render the attributes during serialization. Defaults to C{'toVT102'}. @return: A string expressing the text and display attributes specified by L{output}.
flatten
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_textattributes.py
MIT
def readfile(self, name): """ Return file-like object for name. """ if self.mode not in ("r", "a"): raise RuntimeError('read() requires mode "r" or "a"') if not self.fp: raise RuntimeError( "Attempt to read ZIP archive that was already closed") zinfo = self.getinfo(name) self.fp.seek(zinfo.header_offset, 0) fheader = self.fp.read(_fileHeaderSize) if fheader[0:4] != zipfile.stringFileHeader: raise zipfile.BadZipfile("Bad magic number for file header") fheader = struct.unpack(zipfile.structFileHeader, fheader) fname = self.fp.read(fheader[zipfile._FH_FILENAME_LENGTH]) if fheader[zipfile._FH_EXTRA_FIELD_LENGTH]: self.fp.read(fheader[zipfile._FH_EXTRA_FIELD_LENGTH]) if zinfo.flag_bits & 0x800: # UTF-8 filename fname_str = fname.decode("utf-8") else: fname_str = fname.decode("cp437") if fname_str != zinfo.orig_filename: raise zipfile.BadZipfile( 'File name in directory "%s" and header "%s" differ.' % ( zinfo.orig_filename, fname_str)) if zinfo.compress_type == zipfile.ZIP_STORED: return ZipFileEntry(self, zinfo.compress_size) elif zinfo.compress_type == zipfile.ZIP_DEFLATED: return DeflatedZipFileEntry(self, zinfo.compress_size) else: raise zipfile.BadZipfile( "Unsupported compression method %d for file %s" % (zinfo.compress_type, name))
Return file-like object for name.
readfile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def __init__(self, chunkingZipFile, length): """ Create a L{_FileEntry} from a L{ChunkingZipFile}. """ self.chunkingZipFile = chunkingZipFile self.fp = self.chunkingZipFile.fp self.length = length self.finished = 0 self.closed = False
Create a L{_FileEntry} from a L{ChunkingZipFile}.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def isatty(self): """ Returns false because zip files should not be ttys """ return False
Returns false because zip files should not be ttys
isatty
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def close(self): """ Close self (file-like object) """ self.closed = True self.finished = 1 del self.fp
Close self (file-like object)
close
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def __next__(self): """ Implement next as file does (like readline, except raises StopIteration at EOF) """ nextline = self.readline() if nextline: return nextline raise StopIteration()
Implement next as file does (like readline, except raises StopIteration at EOF)
__next__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def readlines(self): """ Returns a list of all the lines """ return list(self)
Returns a list of all the lines
readlines
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def xreadlines(self): """ Returns an iterator (so self) """ return self
Returns an iterator (so self)
xreadlines
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def countZipFileChunks(filename, chunksize): """ Predict the number of chunks that will be extracted from the entire zipfile, given chunksize blocks. """ totalchunks = 0 zf = ChunkingZipFile(filename) for info in zf.infolist(): totalchunks += countFileChunks(info, chunksize) return totalchunks
Predict the number of chunks that will be extracted from the entire zipfile, given chunksize blocks.
countZipFileChunks
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def countFileChunks(zipinfo, chunksize): """ Count the number of chunks that will result from the given C{ZipInfo}. @param zipinfo: a C{zipfile.ZipInfo} instance describing an entry in a zip archive to be counted. @return: the number of chunks present in the zip file. (Even an empty file counts as one chunk.) @rtype: L{int} """ count, extra = divmod(zipinfo.file_size, chunksize) if extra > 0: count += 1 return count or 1
Count the number of chunks that will result from the given C{ZipInfo}. @param zipinfo: a C{zipfile.ZipInfo} instance describing an entry in a zip archive to be counted. @return: the number of chunks present in the zip file. (Even an empty file counts as one chunk.) @rtype: L{int}
countFileChunks
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def unzipIterChunky(filename, directory='.', overwrite=0, chunksize=4096): """ Return a generator for the zipfile. This implementation will yield after every chunksize uncompressed bytes, or at the end of a file, whichever comes first. The value it yields is the number of chunks left to unzip. """ czf = ChunkingZipFile(filename, 'r') if not os.path.exists(directory): os.makedirs(directory) remaining = countZipFileChunks(filename, chunksize) names = czf.namelist() infos = czf.infolist() for entry, info in zip(names, infos): isdir = info.external_attr & DIR_BIT f = os.path.join(directory, entry) if isdir: # overwrite flag only applies to files if not os.path.exists(f): os.makedirs(f) remaining -= 1 yield remaining else: # create the directory the file will be in first, # since we can't guarantee it exists fdir = os.path.split(f)[0] if not os.path.exists(fdir): os.makedirs(fdir) if overwrite or not os.path.exists(f): fp = czf.readfile(entry) if info.file_size == 0: remaining -= 1 yield remaining with open(f, 'wb') as outfile: while fp.tell() < info.file_size: hunk = fp.read(chunksize) outfile.write(hunk) remaining -= 1 yield remaining else: remaining -= countFileChunks(info, chunksize) yield remaining
Return a generator for the zipfile. This implementation will yield after every chunksize uncompressed bytes, or at the end of a file, whichever comes first. The value it yields is the number of chunks left to unzip.
unzipIterChunky
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/zipstream.py
MIT
def _replaceIf(condition, alternative): """ If C{condition}, replace this function with C{alternative}. @param condition: A L{bool} which says whether this should be replaced. @param alternative: An alternative function that will be swapped in instead of the original, if C{condition} is truthy. @return: A decorator. """ def decorator(func): if condition is True: call = alternative elif condition is False: call = func else: raise ValueError(("condition argument to _replaceIf requires a " "bool, not {}").format(repr(condition))) @wraps(func) def wrapped(*args, **kwargs): return call(*args, **kwargs) return wrapped return decorator
If C{condition}, replace this function with C{alternative}. @param condition: A L{bool} which says whether this should be replaced. @param alternative: An alternative function that will be swapped in instead of the original, if C{condition} is truthy. @return: A decorator.
_replaceIf
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_oldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_oldstyle.py
MIT
def passthru(arg): """ Return C{arg}. Do nothing. @param arg: The arg to return. @return: C{arg} """ return arg
Return C{arg}. Do nothing. @param arg: The arg to return. @return: C{arg}
passthru
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_oldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_oldstyle.py
MIT
def _ensureOldClass(cls): """ Ensure that C{cls} is an old-style class. @param cls: The class to check. @return: The class, if it is an old-style class. @raises: L{ValueError} if it is a new-style class. """ if not type(cls) is types.ClassType: from twisted.python.reflect import fullyQualifiedName raise ValueError( ("twisted.python._oldstyle._oldStyle is being used to decorate a " "new-style class ({cls}). This should only be used to " "decorate old-style classes.").format( cls=fullyQualifiedName(cls))) return cls
Ensure that C{cls} is an old-style class. @param cls: The class to check. @return: The class, if it is an old-style class. @raises: L{ValueError} if it is a new-style class.
_ensureOldClass
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_oldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_oldstyle.py
MIT
def _oldStyle(cls): """ A decorator which conditionally converts old-style classes to new-style classes. If it is Python 3, or if the C{TWISTED_NEWSTYLE} environment variable has a falsey (C{no}, C{false}, C{False}, or C{0}) value in the environment, this decorator is a no-op. @param cls: An old-style class to convert to new-style. @type cls: L{types.ClassType} @return: A new-style version of C{cls}. """ _ensureOldClass(cls) _bases = cls.__bases__ + (object,) return type(cls.__name__, _bases, cls.__dict__)
A decorator which conditionally converts old-style classes to new-style classes. If it is Python 3, or if the C{TWISTED_NEWSTYLE} environment variable has a falsey (C{no}, C{false}, C{False}, or C{0}) value in the environment, this decorator is a no-op. @param cls: An old-style class to convert to new-style. @type cls: L{types.ClassType} @return: A new-style version of C{cls}.
_oldStyle
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_oldstyle.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_oldstyle.py
MIT
def addPatch(self, obj, name, value): """ Add a patch so that the attribute C{name} on C{obj} will be assigned to C{value} when C{patch} is called or during C{runWithPatches}. You can restore the original values with a call to restore(). """ self._patchesToApply.append((obj, name, value))
Add a patch so that the attribute C{name} on C{obj} will be assigned to C{value} when C{patch} is called or during C{runWithPatches}. You can restore the original values with a call to restore().
addPatch
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
MIT
def _alreadyPatched(self, obj, name): """ Has the C{name} attribute of C{obj} already been patched by this patcher? """ for o, n, v in self._originals: if (o, n) == (obj, name): return True return False
Has the C{name} attribute of C{obj} already been patched by this patcher?
_alreadyPatched
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
MIT
def patch(self): """ Apply all of the patches that have been specified with L{addPatch}. Reverse this operation using L{restore}. """ for obj, name, value in self._patchesToApply: if not self._alreadyPatched(obj, name): self._originals.append((obj, name, getattr(obj, name))) setattr(obj, name, value)
Apply all of the patches that have been specified with L{addPatch}. Reverse this operation using L{restore}.
patch
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
MIT
def restore(self): """ Restore all original values to any patched objects. """ while self._originals: obj, name, value = self._originals.pop() setattr(obj, name, value)
Restore all original values to any patched objects.
restore
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
MIT
def runWithPatches(self, f, *args, **kw): """ Apply each patch already specified. Then run the function f with the given args and kwargs. Restore everything when done. """ self.patch() try: return f(*args, **kw) finally: self.restore()
Apply each patch already specified. Then run the function f with the given args and kwargs. Restore everything when done.
runWithPatches
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/monkey.py
MIT
def symlink(value, filename): """ Write a file at C{filename} with the contents of C{value}. See the above comment block as to why this is needed. """ # XXX Implement an atomic thingamajig for win32 newlinkname = filename + "." + unique() + '.newlink' newvalname = os.path.join(newlinkname, "symlink") os.mkdir(newlinkname) # Python 3 does not support the 'commit' flag of fopen in the MSVCRT # (http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx) if _PY3: mode = 'w' else: mode = 'wc' with _open(newvalname, mode) as f: f.write(value) f.flush() try: rename(newlinkname, filename) except: os.remove(newvalname) os.rmdir(newlinkname) raise
Write a file at C{filename} with the contents of C{value}. See the above comment block as to why this is needed.
symlink
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/lockfile.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/lockfile.py
MIT
def readlink(filename): """ Read the contents of C{filename}. See the above comment block as to why this is needed. """ try: fObj = _open(os.path.join(filename, 'symlink'), 'r') except IOError as e: if e.errno == errno.ENOENT or e.errno == errno.EIO: raise OSError(e.errno, None) raise else: with fObj: result = fObj.read() return result
Read the contents of C{filename}. See the above comment block as to why this is needed.
readlink
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/lockfile.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/lockfile.py
MIT
def sh(command, null=True, prompt=False): """ I'll try to execute C{command}, and if C{prompt} is true, I'll ask before running it. If the command returns something other than 0, I'll raise C{CommandFailed(command)}. """ print("--$", command) if prompt: if raw_input("run ?? ").startswith('n'): return if null: command = "%s > /dev/null" % command if os.system(command) != 0: raise CommandFailed(command)
I'll try to execute C{command}, and if C{prompt} is true, I'll ask before running it. If the command returns something other than 0, I'll raise C{CommandFailed(command)}.
sh
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/release.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/release.py
MIT
def _isPythonIdentifier(string): """ cheezy fake test for proper identifier-ness. @param string: a L{str} which might or might not be a valid python identifier. @return: True or False """ textString = nativeString(string) return (' ' not in textString and '.' not in textString and '-' not in textString)
cheezy fake test for proper identifier-ness. @param string: a L{str} which might or might not be a valid python identifier. @return: True or False
_isPythonIdentifier
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def iterModules(self): """ Loop over the modules present below this entry or package on PYTHONPATH. For modules which are not packages, this will yield nothing. For packages and path entries, this will only yield modules one level down; i.e. if there is a package a.b.c, iterModules on a will only return a.b. If you want to descend deeply, use walkModules. @return: a generator which yields PythonModule instances that describe modules which can be, or have been, imported. """ yielded = {} if not self.filePath.exists(): return for placeToLook in self._packagePaths(): try: children = sorted(placeToLook.children()) except UnlistableError: continue for potentialTopLevel in children: ext = potentialTopLevel.splitext()[1] potentialBasename = potentialTopLevel.basename()[:-len(ext)] if ext in PYTHON_EXTENSIONS: # TODO: this should be a little choosier about which path entry # it selects first, and it should do all the .so checking and # crud if not _isPythonIdentifier(potentialBasename): continue modname = self._subModuleName(potentialBasename) if modname.split(".")[-1] == '__init__': # This marks the directory as a package so it can't be # a module. continue if modname not in yielded: yielded[modname] = True pm = PythonModule(modname, potentialTopLevel, self._getEntry()) assert pm != self yield pm else: if (ext or not _isPythonIdentifier(potentialBasename) or not potentialTopLevel.isdir()): continue modname = self._subModuleName(potentialTopLevel.basename()) for ext in PYTHON_EXTENSIONS: initpy = potentialTopLevel.child("__init__"+ext) if initpy.exists() and modname not in yielded: yielded[modname] = True pm = PythonModule(modname, initpy, self._getEntry()) assert pm != self yield pm break
Loop over the modules present below this entry or package on PYTHONPATH. For modules which are not packages, this will yield nothing. For packages and path entries, this will only yield modules one level down; i.e. if there is a package a.b.c, iterModules on a will only return a.b. If you want to descend deeply, use walkModules. @return: a generator which yields PythonModule instances that describe modules which can be, or have been, imported.
iterModules
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def walkModules(self, importPackages=False): """ Similar to L{iterModules}, this yields self, and then every module in my package or entry, and every submodule in each package or entry. In other words, this is deep, and L{iterModules} is shallow. """ yield self for package in self.iterModules(): for module in package.walkModules(importPackages=importPackages): yield module
Similar to L{iterModules}, this yields self, and then every module in my package or entry, and every submodule in each package or entry. In other words, this is deep, and L{iterModules} is shallow.
walkModules
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def _subModuleName(self, mn): """ This is a hook to provide packages with the ability to specify their names as a prefix to submodules here. """ return mn
This is a hook to provide packages with the ability to specify their names as a prefix to submodules here.
_subModuleName
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def _packagePaths(self): """ Implement in subclasses to specify where to look for modules. @return: iterable of FilePath-like objects. """ raise NotImplementedError()
Implement in subclasses to specify where to look for modules. @return: iterable of FilePath-like objects.
_packagePaths
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def _getEntry(self): """ Implement in subclasses to specify what path entry submodules will come from. @return: a PathEntry instance. """ raise NotImplementedError()
Implement in subclasses to specify what path entry submodules will come from. @return: a PathEntry instance.
_getEntry
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __getitem__(self, modname): """ Retrieve a module from below this path or package. @param modname: a str naming a module to be loaded. For entries, this is a top-level, undotted package name, and for packages it is the name of the module without the package prefix. For example, if you have a PythonModule representing the 'twisted' package, you could use:: twistedPackageObj['python']['modules'] to retrieve this module. @raise: KeyError if the module is not found. @return: a PythonModule. """ for module in self.iterModules(): if module.name == self._subModuleName(modname): return module raise KeyError(modname)
Retrieve a module from below this path or package. @param modname: a str naming a module to be loaded. For entries, this is a top-level, undotted package name, and for packages it is the name of the module without the package prefix. For example, if you have a PythonModule representing the 'twisted' package, you could use:: twistedPackageObj['python']['modules'] to retrieve this module. @raise: KeyError if the module is not found. @return: a PythonModule.
__getitem__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __iter__(self): """ Implemented to raise NotImplementedError for clarity, so that attempting to loop over this object won't call __getitem__. Note: in the future there might be some sensible default for iteration, like 'walkEverything', so this is deliberately untested and undefined behavior. """ raise NotImplementedError()
Implemented to raise NotImplementedError for clarity, so that attempting to loop over this object won't call __getitem__. Note: in the future there might be some sensible default for iteration, like 'walkEverything', so this is deliberately untested and undefined behavior.
__iter__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __init__(self, name, onObject, loaded, pythonValue): """ Create a PythonAttribute. This is a private constructor. Do not construct me directly, use PythonModule.iterAttributes. @param name: the FQPN @param onObject: see ivar @param loaded: always True, for now @param pythonValue: the value of the attribute we're pointing to. """ self.name = name self.onObject = onObject self._loaded = loaded self.pythonValue = pythonValue
Create a PythonAttribute. This is a private constructor. Do not construct me directly, use PythonModule.iterAttributes. @param name: the FQPN @param onObject: see ivar @param loaded: always True, for now @param pythonValue: the value of the attribute we're pointing to.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def isLoaded(self): """ Return a boolean describing whether the attribute this describes has actually been loaded into memory by importing its module. Note: this currently always returns true; there is no Python parser support in this module yet. """ return self._loaded
Return a boolean describing whether the attribute this describes has actually been loaded into memory by importing its module. Note: this currently always returns true; there is no Python parser support in this module yet.
isLoaded
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def load(self, default=_nothing): """ Load the value associated with this attribute. @return: an arbitrary Python object, or 'default' if there is an error loading it. """ return self.pythonValue
Load the value associated with this attribute. @return: an arbitrary Python object, or 'default' if there is an error loading it.
load
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __init__(self, name, filePath, pathEntry): """ Create a PythonModule. Do not construct this directly, instead inspect a PythonPath or other PythonModule instances. @param name: see ivar @param filePath: see ivar @param pathEntry: see ivar """ _name = nativeString(name) assert not _name.endswith(".__init__") self.name = _name self.filePath = filePath self.parentPath = filePath.parent() self.pathEntry = pathEntry
Create a PythonModule. Do not construct this directly, instead inspect a PythonPath or other PythonModule instances. @param name: see ivar @param filePath: see ivar @param pathEntry: see ivar
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __repr__(self): """ Return a string representation including the module name. """ return 'PythonModule<%r>' % (self.name,)
Return a string representation including the module name.
__repr__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def isLoaded(self): """ Determine if the module is loaded into sys.modules. @return: a boolean: true if loaded, false if not. """ return self.pathEntry.pythonPath.moduleDict.get(self.name) is not None
Determine if the module is loaded into sys.modules. @return: a boolean: true if loaded, false if not.
isLoaded
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def iterAttributes(self): """ List all the attributes defined in this module. Note: Future work is planned here to make it possible to list python attributes on a module without loading the module by inspecting ASTs or bytecode, but currently any iteration of PythonModule objects insists they must be loaded, and will use inspect.getmodule. @raise NotImplementedError: if this module is not loaded. @return: a generator yielding PythonAttribute instances describing the attributes of this module. """ if not self.isLoaded(): raise NotImplementedError( "You can't load attributes from non-loaded modules yet.") for name, val in inspect.getmembers(self.load()): yield PythonAttribute(self.name+'.'+name, self, True, val)
List all the attributes defined in this module. Note: Future work is planned here to make it possible to list python attributes on a module without loading the module by inspecting ASTs or bytecode, but currently any iteration of PythonModule objects insists they must be loaded, and will use inspect.getmodule. @raise NotImplementedError: if this module is not loaded. @return: a generator yielding PythonAttribute instances describing the attributes of this module.
iterAttributes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def isPackage(self): """ Returns true if this module is also a package, and might yield something from iterModules. """ return _isPackagePath(self.filePath)
Returns true if this module is also a package, and might yield something from iterModules.
isPackage
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def load(self, default=_nothing): """ Load this module. @param default: if specified, the value to return in case of an error. @return: a genuine python module. @raise: any type of exception. Importing modules is a risky business; the erorrs of any code run at module scope may be raised from here, as well as ImportError if something bizarre happened to the system path between the discovery of this PythonModule object and the attempt to import it. If you specify a default, the error will be swallowed entirely, and not logged. @rtype: types.ModuleType. """ try: return self.pathEntry.pythonPath.moduleLoader(self.name) except: # this needs more thought... if default is not _nothing: return default raise
Load this module. @param default: if specified, the value to return in case of an error. @return: a genuine python module. @raise: any type of exception. Importing modules is a risky business; the erorrs of any code run at module scope may be raised from here, as well as ImportError if something bizarre happened to the system path between the discovery of this PythonModule object and the attempt to import it. If you specify a default, the error will be swallowed entirely, and not logged. @rtype: types.ModuleType.
load
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __eq__(self, other): """ PythonModules with the same name are equal. """ if not isinstance(other, PythonModule): return False return other.name == self.name
PythonModules with the same name are equal.
__eq__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __ne__(self, other): """ PythonModules with different names are not equal. """ if not isinstance(other, PythonModule): return True return other.name != self.name
PythonModules with different names are not equal.
__ne__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def _subModuleName(self, mn): """ submodules of this module are prefixed with our name. """ return self.name + '.' + mn
submodules of this module are prefixed with our name.
_subModuleName
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def _packagePaths(self): """ Yield a sequence of FilePath-like objects which represent path segments. """ if not self.isPackage(): return if self.isLoaded(): load = self.load() if hasattr(load, '__path__'): for fn in load.__path__: if fn == self.parentPath.path: # this should _really_ exist. assert self.parentPath.exists() yield self.parentPath else: smp = self.pathEntry.pythonPath._smartPath(fn) if smp.exists(): yield smp else: yield self.parentPath
Yield a sequence of FilePath-like objects which represent path segments.
_packagePaths
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __init__(self, filePath, pythonPath): """ Create a PathEntry. This is a private constructor. """ self.filePath = filePath self.pythonPath = pythonPath
Create a PathEntry. This is a private constructor.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def mapPath(self, pathLikeString): """ Return a FilePath-like object. @param pathLikeString: a path-like string, like one that might be passed to an import hook. @return: a L{FilePath}, or something like it (currently only a L{ZipPath}, but more might be added later). """
Return a FilePath-like object. @param pathLikeString: a path-like string, like one that might be passed to an import hook. @return: a L{FilePath}, or something like it (currently only a L{ZipPath}, but more might be added later).
mapPath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def mapPath(self, fsPathString): """ Map the given FS path to a ZipPath, by looking at the ZipImporter's "archive" attribute and using it as our ZipArchive root, then walking down into the archive from there. @return: a L{zippath.ZipPath} or L{zippath.ZipArchive} instance. """ za = ZipArchive(self.importer.archive) myPath = FilePath(self.importer.archive) itsPath = FilePath(fsPathString) if myPath == itsPath: return za # This is NOT a general-purpose rule for sys.path or __file__: # zipimport specifically uses regular OS path syntax in its # pathnames, even though zip files specify that slashes are always # the separator, regardless of platform. segs = itsPath.segmentsFrom(myPath) zp = za for seg in segs: zp = zp.child(seg) return zp
Map the given FS path to a ZipPath, by looking at the ZipImporter's "archive" attribute and using it as our ZipArchive root, then walking down into the archive from there. @return: a L{zippath.ZipPath} or L{zippath.ZipArchive} instance.
mapPath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def _defaultSysPathFactory(): """ Provide the default behavior of PythonPath's sys.path factory, which is to return the current value of sys.path. @return: L{sys.path} """ return sys.path
Provide the default behavior of PythonPath's sys.path factory, which is to return the current value of sys.path. @return: L{sys.path}
_defaultSysPathFactory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def __init__(self, sysPath=None, moduleDict=sys.modules, sysPathHooks=sys.path_hooks, importerCache=sys.path_importer_cache, moduleLoader=namedAny, sysPathFactory=None): """ Create a PythonPath. You almost certainly want to use modules.theSystemPath, or its aliased methods, rather than creating a new instance yourself, though. All parameters are optional, and if unspecified, will use 'system' equivalents that makes this PythonPath like the global L{theSystemPath} instance. @param sysPath: a sys.path-like list to use for this PythonPath, to specify where to load modules from. @param moduleDict: a sys.modules-like dictionary to use for keeping track of what modules this PythonPath has loaded. @param sysPathHooks: sys.path_hooks-like list of PEP-302 path hooks to be used for this PythonPath, to determie which importers should be used. @param importerCache: a sys.path_importer_cache-like list of PEP-302 importers. This will be used in conjunction with the given sysPathHooks. @param moduleLoader: a module loader function which takes a string and returns a module. That is to say, it is like L{namedAny} - *not* like L{__import__}. @param sysPathFactory: a 0-argument callable which returns the current value of a sys.path-like list of strings. Specify either this, or sysPath, not both. This alternative interface is provided because the way the Python import mechanism works, you can re-bind the 'sys.path' name and that is what is used for current imports, so it must be a factory rather than a value to deal with modification by rebinding rather than modification by mutation. Note: it is not recommended to rebind sys.path. Although this mechanism can deal with that, it is a subtle point which some tools that it is easy for tools which interact with sys.path to miss. """ if sysPath is not None: sysPathFactory = lambda : sysPath elif sysPathFactory is None: sysPathFactory = _defaultSysPathFactory self._sysPathFactory = sysPathFactory self._sysPath = sysPath self.moduleDict = moduleDict self.sysPathHooks = sysPathHooks self.importerCache = importerCache self.moduleLoader = moduleLoader
Create a PythonPath. You almost certainly want to use modules.theSystemPath, or its aliased methods, rather than creating a new instance yourself, though. All parameters are optional, and if unspecified, will use 'system' equivalents that makes this PythonPath like the global L{theSystemPath} instance. @param sysPath: a sys.path-like list to use for this PythonPath, to specify where to load modules from. @param moduleDict: a sys.modules-like dictionary to use for keeping track of what modules this PythonPath has loaded. @param sysPathHooks: sys.path_hooks-like list of PEP-302 path hooks to be used for this PythonPath, to determie which importers should be used. @param importerCache: a sys.path_importer_cache-like list of PEP-302 importers. This will be used in conjunction with the given sysPathHooks. @param moduleLoader: a module loader function which takes a string and returns a module. That is to say, it is like L{namedAny} - *not* like L{__import__}. @param sysPathFactory: a 0-argument callable which returns the current value of a sys.path-like list of strings. Specify either this, or sysPath, not both. This alternative interface is provided because the way the Python import mechanism works, you can re-bind the 'sys.path' name and that is what is used for current imports, so it must be a factory rather than a value to deal with modification by rebinding rather than modification by mutation. Note: it is not recommended to rebind sys.path. Although this mechanism can deal with that, it is a subtle point which some tools that it is easy for tools which interact with sys.path to miss.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT
def _getSysPath(self): """ Retrieve the current value of the module search path list. """ return self._sysPathFactory()
Retrieve the current value of the module search path list.
_getSysPath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py
MIT