response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Register an adapter class.
An adapter class is expected to implement the given interface, by
adapting instances implementing 'origInterface'. An adapter class's
__init__ method should accept one parameter, an instance implementing
'origInterface'. | def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
"""Register an adapter class.
An adapter class is expected to implement the given interface, by
adapting instances implementing 'origInterface'. An adapter class's
__init__ method should accept one parameter, an instance implementing
'origInterface'.
"""
self = globalRegistry
assert interfaceClasses, "You need to pass an Interface"
global ALLOW_DUPLICATES
# deal with class->interface adapters:
if not isinstance(origInterface, interface.InterfaceClass):
origInterface = declarations.implementedBy(origInterface)
for interfaceClass in interfaceClasses:
factory = self.registered([origInterface], interfaceClass)
if factory is not None and not ALLOW_DUPLICATES:
raise ValueError(f"an adapter ({factory}) was already registered.")
for interfaceClass in interfaceClasses:
self.register([origInterface], interfaceClass, "", adapterFactory) |
Return registered adapter for a given class and interface.
Note that is tied to the *Twisted* global registry, and will
thus not find adapters registered elsewhere. | def getAdapterFactory(fromInterface, toInterface, default):
"""Return registered adapter for a given class and interface.
Note that is tied to the *Twisted* global registry, and will
thus not find adapters registered elsewhere.
"""
self = globalRegistry
if not isinstance(fromInterface, interface.InterfaceClass):
fromInterface = declarations.implementedBy(fromInterface)
factory = self.lookup1(fromInterface, toInterface) # type: ignore[attr-defined]
if factory is None:
factory = default
return factory |
Add an adapter hook which will attempt to look up adapters in the given
registry.
@type registry: L{zope.interface.adapter.AdapterRegistry}
@return: The hook which was added, for later use with L{_removeHook}. | def _addHook(registry):
"""
Add an adapter hook which will attempt to look up adapters in the given
registry.
@type registry: L{zope.interface.adapter.AdapterRegistry}
@return: The hook which was added, for later use with L{_removeHook}.
"""
lookup = registry.lookup1
def _hook(iface, ob):
factory = lookup(declarations.providedBy(ob), iface)
if factory is None:
return None
else:
return factory(ob)
interface.adapter_hooks.append(_hook)
return _hook |
Remove a previously added adapter hook.
@param hook: An object previously returned by a call to L{_addHook}. This
will be removed from the list of adapter hooks. | def _removeHook(hook):
"""
Remove a previously added adapter hook.
@param hook: An object previously returned by a call to L{_addHook}. This
will be removed from the list of adapter hooks.
"""
interface.adapter_hooks.remove(hook) |
Returns the Twisted global
C{zope.interface.adapter.AdapterRegistry} instance. | def getRegistry():
"""Returns the Twisted global
C{zope.interface.adapter.AdapterRegistry} instance.
"""
return globalRegistry |
Create a class which proxies all method calls which adhere to an interface
to another provider of that interface.
This function is intended for creating specialized proxies. The typical way
to use it is by subclassing the result::
class MySpecializedProxy(proxyForInterface(IFoo)):
def someInterfaceMethod(self, arg):
if arg == 3:
return 3
return self.original.someInterfaceMethod(arg)
@param iface: The Interface to which the resulting object will conform, and
which the wrapped object must provide.
@param originalAttribute: name of the attribute used to save the original
object in the resulting class. Default to C{original}.
@type originalAttribute: C{str}
@return: A class whose constructor takes the original object as its only
argument. Constructing the class creates the proxy. | def proxyForInterface(iface, originalAttribute="original"):
"""
Create a class which proxies all method calls which adhere to an interface
to another provider of that interface.
This function is intended for creating specialized proxies. The typical way
to use it is by subclassing the result::
class MySpecializedProxy(proxyForInterface(IFoo)):
def someInterfaceMethod(self, arg):
if arg == 3:
return 3
return self.original.someInterfaceMethod(arg)
@param iface: The Interface to which the resulting object will conform, and
which the wrapped object must provide.
@param originalAttribute: name of the attribute used to save the original
object in the resulting class. Default to C{original}.
@type originalAttribute: C{str}
@return: A class whose constructor takes the original object as its only
argument. Constructing the class creates the proxy.
"""
def __init__(self, original):
setattr(self, originalAttribute, original)
contents: Dict[str, object] = {"__init__": __init__}
for name in iface:
contents[name] = _ProxyDescriptor(name, originalAttribute)
proxy = type(f"(Proxy for {reflect.qual(iface)})", (object,), contents)
# mypy-zope declarations.classImplements only works when passing
# a concrete class type
declarations.classImplements(proxy, iface) # type: ignore[misc]
return proxy |
Return the fully qualified name of a module, class, method or function.
Classes and functions need to be module level ones to be correctly
qualified.
@rtype: C{str}. | def _fullyQualifiedName(obj):
"""
Return the fully qualified name of a module, class, method or function.
Classes and functions need to be module level ones to be correctly
qualified.
@rtype: C{str}.
"""
try:
name = obj.__qualname__
except AttributeError:
name = obj.__name__
if inspect.isclass(obj) or inspect.isfunction(obj):
moduleName = obj.__module__
return f"{moduleName}.{name}"
elif inspect.ismethod(obj):
return f"{obj.__module__}.{obj.__qualname__}"
return name |
Surround a replacement for a deprecated API with some polite text exhorting
the user to consider it as an alternative.
@type replacement: C{str} or callable
@return: a string like "please use twisted.python.modules.getModule
instead". | def _getReplacementString(replacement):
"""
Surround a replacement for a deprecated API with some polite text exhorting
the user to consider it as an alternative.
@type replacement: C{str} or callable
@return: a string like "please use twisted.python.modules.getModule
instead".
"""
if callable(replacement):
replacement = _fullyQualifiedName(replacement)
return f"please use {replacement} instead" |
Generate an addition to a deprecated object's docstring that explains its
deprecation.
@param version: the version it was deprecated.
@type version: L{incremental.Version}
@param replacement: The replacement, if specified.
@type replacement: C{str} or callable
@return: a string like "Deprecated in Twisted 27.2.0; please use
twisted.timestream.tachyon.flux instead." | def _getDeprecationDocstring(version, replacement=None):
"""
Generate an addition to a deprecated object's docstring that explains its
deprecation.
@param version: the version it was deprecated.
@type version: L{incremental.Version}
@param replacement: The replacement, if specified.
@type replacement: C{str} or callable
@return: a string like "Deprecated in Twisted 27.2.0; please use
twisted.timestream.tachyon.flux instead."
"""
doc = f"Deprecated in {getVersionString(version)}"
if replacement:
doc = f"{doc}; {_getReplacementString(replacement)}"
return doc + "." |
Return a string indicating that the Python name was deprecated in the given
version.
@param fqpn: Fully qualified Python name of the thing being deprecated
@type fqpn: C{str}
@param version: Version that C{fqpn} was deprecated in.
@type version: L{incremental.Version}
@param format: A user-provided format to interpolate warning values into, or
L{DEPRECATION_WARNING_FORMAT
<twisted.python.deprecate.DEPRECATION_WARNING_FORMAT>} if L{None} is
given.
@type format: C{str}
@param replacement: what should be used in place of C{fqpn}. Either pass in
a string, which will be inserted into the warning message, or a
callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
@return: A textual description of the deprecation
@rtype: C{str} | def _getDeprecationWarningString(fqpn, version, format=None, replacement=None):
"""
Return a string indicating that the Python name was deprecated in the given
version.
@param fqpn: Fully qualified Python name of the thing being deprecated
@type fqpn: C{str}
@param version: Version that C{fqpn} was deprecated in.
@type version: L{incremental.Version}
@param format: A user-provided format to interpolate warning values into, or
L{DEPRECATION_WARNING_FORMAT
<twisted.python.deprecate.DEPRECATION_WARNING_FORMAT>} if L{None} is
given.
@type format: C{str}
@param replacement: what should be used in place of C{fqpn}. Either pass in
a string, which will be inserted into the warning message, or a
callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
@return: A textual description of the deprecation
@rtype: C{str}
"""
if format is None:
format = DEPRECATION_WARNING_FORMAT
warningString = format % {"fqpn": fqpn, "version": getVersionString(version)}
if replacement:
warningString = "{}; {}".format(
warningString, _getReplacementString(replacement)
)
return warningString |
Return a string indicating that the callable was deprecated in the given
version.
@type callableThing: C{callable}
@param callableThing: Callable object to be deprecated
@type version: L{incremental.Version}
@param version: Version that C{callableThing} was deprecated in.
@type format: C{str}
@param format: A user-provided format to interpolate warning values into,
or L{DEPRECATION_WARNING_FORMAT
<twisted.python.deprecate.DEPRECATION_WARNING_FORMAT>} if L{None} is
given
@param replacement: what should be used in place of the callable. Either
pass in a string, which will be inserted into the warning message,
or a callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
@return: A string describing the deprecation.
@rtype: C{str} | def getDeprecationWarningString(callableThing, version, format=None, replacement=None):
"""
Return a string indicating that the callable was deprecated in the given
version.
@type callableThing: C{callable}
@param callableThing: Callable object to be deprecated
@type version: L{incremental.Version}
@param version: Version that C{callableThing} was deprecated in.
@type format: C{str}
@param format: A user-provided format to interpolate warning values into,
or L{DEPRECATION_WARNING_FORMAT
<twisted.python.deprecate.DEPRECATION_WARNING_FORMAT>} if L{None} is
given
@param replacement: what should be used in place of the callable. Either
pass in a string, which will be inserted into the warning message,
or a callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
@return: A string describing the deprecation.
@rtype: C{str}
"""
return _getDeprecationWarningString(
_fullyQualifiedName(callableThing), version, format, replacement
) |
Append the given text to the docstring of C{thingWithDoc}.
If C{thingWithDoc} has no docstring, then the text just replaces the
docstring. If it has a single-line docstring then it appends a blank line
and the message text. If it has a multi-line docstring, then in appends a
blank line a the message text, and also does the indentation correctly. | def _appendToDocstring(thingWithDoc, textToAppend):
"""
Append the given text to the docstring of C{thingWithDoc}.
If C{thingWithDoc} has no docstring, then the text just replaces the
docstring. If it has a single-line docstring then it appends a blank line
and the message text. If it has a multi-line docstring, then in appends a
blank line a the message text, and also does the indentation correctly.
"""
if thingWithDoc.__doc__:
docstringLines = thingWithDoc.__doc__.splitlines()
else:
docstringLines = []
if len(docstringLines) == 0:
docstringLines.append(textToAppend)
elif len(docstringLines) == 1:
docstringLines.extend(["", textToAppend, ""])
else:
spaces = docstringLines.pop()
docstringLines.extend(["", spaces + textToAppend, spaces])
thingWithDoc.__doc__ = "\n".join(docstringLines) |
Return a decorator that marks callables as deprecated. To deprecate a
property, see L{deprecatedProperty}.
@type version: L{incremental.Version}
@param version: The version in which the callable will be marked as
having been deprecated. The decorated function will be annotated
with this version, having it set as its C{deprecatedVersion}
attribute.
@param replacement: what should be used in place of the callable. Either
pass in a string, which will be inserted into the warning message,
or a callable, which will be expanded to its full import path.
@type replacement: C{str} or callable | def deprecated(
version: Version, replacement: str | Callable[..., object] | None = None
) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
"""
Return a decorator that marks callables as deprecated. To deprecate a
property, see L{deprecatedProperty}.
@type version: L{incremental.Version}
@param version: The version in which the callable will be marked as
having been deprecated. The decorated function will be annotated
with this version, having it set as its C{deprecatedVersion}
attribute.
@param replacement: what should be used in place of the callable. Either
pass in a string, which will be inserted into the warning message,
or a callable, which will be expanded to its full import path.
@type replacement: C{str} or callable
"""
def deprecationDecorator(function: Callable[_P, _R]) -> Callable[_P, _R]:
"""
Decorator that marks C{function} as deprecated.
"""
warningString = getDeprecationWarningString(
function, version, None, replacement
)
@wraps(function)
def deprecatedFunction(*args: _P.args, **kwargs: _P.kwargs) -> _R:
warn(warningString, DeprecationWarning, stacklevel=2)
return function(*args, **kwargs)
_appendToDocstring(
deprecatedFunction, _getDeprecationDocstring(version, replacement)
)
deprecatedFunction.deprecatedVersion = version # type: ignore[attr-defined]
return deprecatedFunction
return deprecationDecorator |
Return a decorator that marks a property as deprecated. To deprecate a
regular callable or class, see L{deprecated}.
@type version: L{incremental.Version}
@param version: The version in which the callable will be marked as
having been deprecated. The decorated function will be annotated
with this version, having it set as its C{deprecatedVersion}
attribute.
@param replacement: what should be used in place of the callable.
Either pass in a string, which will be inserted into the warning
message, or a callable, which will be expanded to its full import
path.
@type replacement: C{str} or callable
@return: A new property with deprecated setter and getter.
@rtype: C{property}
@since: 16.1.0 | def deprecatedProperty(version, replacement=None):
"""
Return a decorator that marks a property as deprecated. To deprecate a
regular callable or class, see L{deprecated}.
@type version: L{incremental.Version}
@param version: The version in which the callable will be marked as
having been deprecated. The decorated function will be annotated
with this version, having it set as its C{deprecatedVersion}
attribute.
@param replacement: what should be used in place of the callable.
Either pass in a string, which will be inserted into the warning
message, or a callable, which will be expanded to its full import
path.
@type replacement: C{str} or callable
@return: A new property with deprecated setter and getter.
@rtype: C{property}
@since: 16.1.0
"""
class _DeprecatedProperty(property):
"""
Extension of the build-in property to allow deprecated setters.
"""
def _deprecatedWrapper(self, function):
@wraps(function)
def deprecatedFunction(*args, **kwargs):
warn(
self.warningString, # type: ignore[attr-defined]
DeprecationWarning,
stacklevel=2,
)
return function(*args, **kwargs)
return deprecatedFunction
def setter(self, function):
return property.setter(self, self._deprecatedWrapper(function))
def deprecationDecorator(function):
warningString = getDeprecationWarningString(
function, version, None, replacement
)
@wraps(function)
def deprecatedFunction(*args, **kwargs):
warn(warningString, DeprecationWarning, stacklevel=2)
return function(*args, **kwargs)
_appendToDocstring(
deprecatedFunction, _getDeprecationDocstring(version, replacement)
)
deprecatedFunction.deprecatedVersion = version # type: ignore[attr-defined]
result = _DeprecatedProperty(deprecatedFunction)
result.warningString = warningString # type: ignore[attr-defined]
return result
return deprecationDecorator |
Return the warning method currently used to record deprecation warnings. | def getWarningMethod():
"""
Return the warning method currently used to record deprecation warnings.
"""
return warn |
Set the warning method to use to record deprecation warnings.
The callable should take message, category and stacklevel. The return
value is ignored. | def setWarningMethod(newMethod):
"""
Set the warning method to use to record deprecation warnings.
The callable should take message, category and stacklevel. The return
value is ignored.
"""
global warn
warn = newMethod |
Mark a module-level attribute as being deprecated.
@type proxy: L{_ModuleProxy}
@param proxy: The module proxy instance proxying the deprecated attributes
@type name: C{str}
@param name: Attribute name
@type version: L{incremental.Version}
@param version: Version that the attribute was deprecated in
@type message: C{str}
@param message: Deprecation message | def _deprecateAttribute(proxy, name, version, message):
"""
Mark a module-level attribute as being deprecated.
@type proxy: L{_ModuleProxy}
@param proxy: The module proxy instance proxying the deprecated attributes
@type name: C{str}
@param name: Attribute name
@type version: L{incremental.Version}
@param version: Version that the attribute was deprecated in
@type message: C{str}
@param message: Deprecation message
"""
_module = object.__getattribute__(proxy, "_module")
attr = _DeprecatedAttribute(_module, name, version, message)
# Add a deprecated attribute marker for this module's attribute. When this
# attribute is accessed via _ModuleProxy a warning is emitted.
_deprecatedAttributes = object.__getattribute__(proxy, "_deprecatedAttributes")
_deprecatedAttributes[name] = attr |
Declare a module-level attribute as being deprecated.
@type version: L{incremental.Version}
@param version: Version that the attribute was deprecated in
@type message: C{str}
@param message: Deprecation message
@type moduleName: C{str}
@param moduleName: Fully-qualified Python name of the module containing
the deprecated attribute; if called from the same module as the
attributes are being deprecated in, using the C{__name__} global can
be helpful
@type name: C{str}
@param name: Attribute name to deprecate | def deprecatedModuleAttribute(version, message, moduleName, name):
"""
Declare a module-level attribute as being deprecated.
@type version: L{incremental.Version}
@param version: Version that the attribute was deprecated in
@type message: C{str}
@param message: Deprecation message
@type moduleName: C{str}
@param moduleName: Fully-qualified Python name of the module containing
the deprecated attribute; if called from the same module as the
attributes are being deprecated in, using the C{__name__} global can
be helpful
@type name: C{str}
@param name: Attribute name to deprecate
"""
module = sys.modules[moduleName]
if not isinstance(module, _ModuleProxy):
module = cast(ModuleType, _ModuleProxy(module))
sys.modules[moduleName] = module
_deprecateAttribute(module, name, version, message) |
Issue a warning string, identifying C{offender} as the responsible code.
This function is used to deprecate some behavior of a function. It differs
from L{warnings.warn} in that it is not limited to deprecating the behavior
of a function currently on the call stack.
@param offender: The function that is being deprecated.
@param warningString: The string that should be emitted by this warning.
@type warningString: C{str}
@since: 11.0 | def warnAboutFunction(offender, warningString):
"""
Issue a warning string, identifying C{offender} as the responsible code.
This function is used to deprecate some behavior of a function. It differs
from L{warnings.warn} in that it is not limited to deprecating the behavior
of a function currently on the call stack.
@param offender: The function that is being deprecated.
@param warningString: The string that should be emitted by this warning.
@type warningString: C{str}
@since: 11.0
"""
# inspect.getmodule() is attractive, but somewhat
# broken in Python < 2.6. See Python bug 4845.
# In Python 3.13 line numbers returned by findlinestarts
# can be None for bytecode that does not map to source
# lines.
offenderModule = sys.modules[offender.__module__]
warn_explicit(
warningString,
category=DeprecationWarning,
filename=inspect.getabsfile(offenderModule),
lineno=max(
lineNumber
for _, lineNumber in findlinestarts(offender.__code__)
if lineNumber is not None
),
module=offenderModule.__name__,
registry=offender.__globals__.setdefault("__warningregistry__", {}),
module_globals=None,
) |
Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param argspec: The argument specification for the function to inspect.
@type argspec: I{inspect.ArgSpec}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in C{argspec})
to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object} | def _passedArgSpec(argspec, positional, keyword):
"""
Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param argspec: The argument specification for the function to inspect.
@type argspec: I{inspect.ArgSpec}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in C{argspec})
to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object}
"""
result: Dict[str, object] = {}
unpassed = len(argspec.args) - len(positional)
if argspec.keywords is not None:
kwargs = result[argspec.keywords] = {}
if unpassed < 0:
if argspec.varargs is None:
raise TypeError("Too many arguments.")
else:
result[argspec.varargs] = positional[len(argspec.args) :]
for name, value in zip(argspec.args, positional):
result[name] = value
for name, value in keyword.items():
if name in argspec.args:
if name in result:
raise TypeError("Already passed.")
result[name] = value
elif argspec.keywords is not None:
kwargs[name] = value
else:
raise TypeError("no such param")
return result |
Take an L{inspect.Signature}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param signature: The signature of the function to inspect.
@type signature: L{inspect.Signature}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in
C{signature}) to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object} | def _passedSignature(signature, positional, keyword):
"""
Take an L{inspect.Signature}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param signature: The signature of the function to inspect.
@type signature: L{inspect.Signature}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in
C{signature}) to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object}
"""
result = {}
kwargs = None
numPositional = 0
for n, (name, param) in enumerate(signature.parameters.items()):
if param.kind == inspect.Parameter.VAR_POSITIONAL:
# Varargs, for example: *args
result[name] = positional[n:]
numPositional = len(result[name]) + 1
elif param.kind == inspect.Parameter.VAR_KEYWORD:
# Variable keyword args, for example: **my_kwargs
kwargs = result[name] = {}
elif param.kind in (
inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.POSITIONAL_ONLY,
):
if n < len(positional):
result[name] = positional[n]
numPositional += 1
elif param.kind == inspect.Parameter.KEYWORD_ONLY:
if name not in keyword:
if param.default == inspect.Parameter.empty:
raise TypeError(f"missing keyword arg {name}")
else:
result[name] = param.default
else:
raise TypeError(f"'{name}' parameter is invalid kind: {param.kind}")
if len(positional) > numPositional:
raise TypeError("Too many arguments.")
for name, value in keyword.items():
if name in signature.parameters.keys():
if name in result:
raise TypeError("Already passed.")
result[name] = value
elif kwargs is not None:
kwargs[name] = value
else:
raise TypeError("no such param")
return result |
Decorator which causes its decoratee to raise a L{TypeError} if two of the
given arguments are passed at the same time.
@param argumentPairs: pairs of argument identifiers, each pair indicating
an argument that may not be passed in conjunction with another.
@type argumentPairs: sequence of 2-sequences of L{str}
@return: A decorator, used like so::
@_mutuallyExclusiveArguments([["tweedledum", "tweedledee"]])
def function(tweedledum=1, tweedledee=2):
"Don't pass tweedledum and tweedledee at the same time."
@rtype: 1-argument callable taking a callable and returning a callable. | def _mutuallyExclusiveArguments(argumentPairs):
"""
Decorator which causes its decoratee to raise a L{TypeError} if two of the
given arguments are passed at the same time.
@param argumentPairs: pairs of argument identifiers, each pair indicating
an argument that may not be passed in conjunction with another.
@type argumentPairs: sequence of 2-sequences of L{str}
@return: A decorator, used like so::
@_mutuallyExclusiveArguments([["tweedledum", "tweedledee"]])
def function(tweedledum=1, tweedledee=2):
"Don't pass tweedledum and tweedledee at the same time."
@rtype: 1-argument callable taking a callable and returning a callable.
"""
def wrapper(wrappee):
spec = inspect.signature(wrappee)
_passed = _passedSignature
@wraps(wrappee)
def wrapped(*args, **kwargs):
arguments = _passed(spec, args, kwargs)
for this, that in argumentPairs:
if this in arguments and that in arguments:
raise TypeError(
("The %r and %r arguments to %s " "are mutually exclusive.")
% (this, that, _fullyQualifiedName(wrappee))
)
return wrappee(*args, **kwargs)
return wrapped
return wrapper |
Return a decorator that marks a keyword parameter of a callable
as deprecated. A warning will be emitted if a caller supplies
a value for the parameter, whether the caller uses a keyword or
positional syntax.
@type version: L{incremental.Version}
@param version: The version in which the parameter will be marked as
having been deprecated.
@type name: L{str}
@param name: The name of the deprecated parameter.
@type replacement: L{str}
@param replacement: Optional text indicating what should be used in
place of the deprecated parameter.
@since: Twisted 21.2.0 | def deprecatedKeywordParameter(
version: Version, name: str, replacement: Optional[str] = None
) -> Callable[[_Tc], _Tc]:
"""
Return a decorator that marks a keyword parameter of a callable
as deprecated. A warning will be emitted if a caller supplies
a value for the parameter, whether the caller uses a keyword or
positional syntax.
@type version: L{incremental.Version}
@param version: The version in which the parameter will be marked as
having been deprecated.
@type name: L{str}
@param name: The name of the deprecated parameter.
@type replacement: L{str}
@param replacement: Optional text indicating what should be used in
place of the deprecated parameter.
@since: Twisted 21.2.0
"""
def wrapper(wrappee: _Tc) -> _Tc:
warningString = _getDeprecationWarningString(
f"The {name!r} parameter to {_fullyQualifiedName(wrappee)}",
version,
replacement=replacement,
)
doc = "The {!r} parameter was deprecated in {}".format(
name,
getVersionString(version),
)
if replacement:
doc = doc + "; " + _getReplacementString(replacement)
doc += "."
params = inspect.signature(wrappee).parameters
if (
name in params
and params[name].kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
):
parameterIndex = list(params).index(name)
def checkDeprecatedParameter(*args, **kwargs):
if len(args) > parameterIndex or name in kwargs:
warn(warningString, DeprecationWarning, stacklevel=2)
return wrappee(*args, **kwargs)
else:
def checkDeprecatedParameter(*args, **kwargs):
if name in kwargs:
warn(warningString, DeprecationWarning, stacklevel=2)
return wrappee(*args, **kwargs)
decorated = cast(_Tc, wraps(wrappee)(checkDeprecatedParameter))
_appendToDocstring(decorated, doc)
return decorated
return wrapper |
Format and write frames.
@param frames: is a list of frames as used by Failure.frames, with
each frame being a list of
(funcName, fileName, lineNumber, locals.items(), globals.items())
@type frames: list
@param write: this will be called with formatted strings.
@type write: callable
@param detail: Four detail levels are available:
default, brief, verbose, and verbose-vars-not-captured.
C{Failure.printDetailedTraceback} uses the latter when the caller asks
for verbose, but no vars were captured, so that an explicit warning
about the missing data is shown.
@type detail: string | def format_frames(frames, write, detail="default"):
"""
Format and write frames.
@param frames: is a list of frames as used by Failure.frames, with
each frame being a list of
(funcName, fileName, lineNumber, locals.items(), globals.items())
@type frames: list
@param write: this will be called with formatted strings.
@type write: callable
@param detail: Four detail levels are available:
default, brief, verbose, and verbose-vars-not-captured.
C{Failure.printDetailedTraceback} uses the latter when the caller asks
for verbose, but no vars were captured, so that an explicit warning
about the missing data is shown.
@type detail: string
"""
if detail not in ("default", "brief", "verbose", "verbose-vars-not-captured"):
raise ValueError(
"Detail must be default, brief, verbose, or "
"verbose-vars-not-captured. (not %r)" % (detail,)
)
w = write
if detail == "brief":
for method, filename, lineno, localVars, globalVars in frames:
w(f"{filename}:{lineno}:{method}\n")
elif detail == "default":
for method, filename, lineno, localVars, globalVars in frames:
w(f' File "{filename}", line {lineno}, in {method}\n')
w(" %s\n" % linecache.getline(filename, lineno).strip())
elif detail == "verbose-vars-not-captured":
for method, filename, lineno, localVars, globalVars in frames:
w("%s:%d: %s(...)\n" % (filename, lineno, method))
w(" [Capture of Locals and Globals disabled (use captureVars=True)]\n")
elif detail == "verbose":
for method, filename, lineno, localVars, globalVars in frames:
w("%s:%d: %s(...)\n" % (filename, lineno, method))
w(" [ Locals ]\n")
# Note: the repr(val) was (self.pickled and val) or repr(val)))
for name, val in localVars:
w(f" {name} : {repr(val)}\n")
w(" ( Globals )\n")
for name, val in globalVars:
w(f" {name} : {repr(val)}\n") |
Construct a fake traceback object using a list of frames.
It should have the same API as stdlib to allow interaction with
other tools.
@param stackFrames: [(methodname, filename, lineno, locals, globals), ...]
@param tbFrames: [(methodname, filename, lineno, locals, globals), ...] | def _Traceback(stackFrames, tbFrames):
"""
Construct a fake traceback object using a list of frames.
It should have the same API as stdlib to allow interaction with
other tools.
@param stackFrames: [(methodname, filename, lineno, locals, globals), ...]
@param tbFrames: [(methodname, filename, lineno, locals, globals), ...]
"""
assert len(tbFrames) > 0, "Must pass some frames"
# We deliberately avoid using recursion here, as the frames list may be
# long.
# 'stackFrames' is a list of frames above (ie, older than) the point the
# exception was caught, with oldest at the start. Start by building these
# into a linked list of _Frame objects (with the f_back links pointing back
# towards the oldest frame).
stack = None
for sf in stackFrames:
stack = _Frame(sf, stack)
# 'tbFrames' is a list of frames from the point the exception was caught,
# down to where it was thrown, with the oldest at the start. Add these to
# the linked list of _Frames, but also wrap each one with a _Traceback
# frame which is linked in the opposite direction (towards the newest
# frame).
stack = _Frame(tbFrames[0], stack)
firstTb = tb = _TracebackFrame(stack)
for sf in tbFrames[1:]:
stack = _Frame(sf, stack)
tb.tb_next = _TracebackFrame(stack)
tb = tb.tb_next
# Return the first _TracebackFrame.
return firstTb |
Mark the given callable as extraneous to inlineCallbacks exception
reporting; don't show these functions.
@param f: a function that you NEVER WANT TO SEE AGAIN in ANY TRACEBACK
reported by Failure.
@type f: function
@return: f | def _extraneous(f: _T_Callable) -> _T_Callable:
"""
Mark the given callable as extraneous to inlineCallbacks exception
reporting; don't show these functions.
@param f: a function that you NEVER WANT TO SEE AGAIN in ANY TRACEBACK
reported by Failure.
@type f: function
@return: f
"""
_inlineCallbacksExtraneous.append(f.__code__)
return f |
Convert a list of (name, object) pairs into (name, repr) pairs.
L{twisted.python.reflect.safe_repr} is used to generate the repr, so no
exceptions will be raised by faulty C{__repr__} methods.
@param varsDictItems: a sequence of (name, value) pairs as returned by e.g.
C{locals().items()}.
@returns: a sequence of (name, repr) pairs. | def _safeReprVars(varsDictItems):
"""
Convert a list of (name, object) pairs into (name, repr) pairs.
L{twisted.python.reflect.safe_repr} is used to generate the repr, so no
exceptions will be raised by faulty C{__repr__} methods.
@param varsDictItems: a sequence of (name, value) pairs as returned by e.g.
C{locals().items()}.
@returns: a sequence of (name, repr) pairs.
"""
return [(name, reflect.safe_repr(obj)) for (name, obj) in varsDictItems] |
Initialize failure object, possibly spawning pdb. | def _debuginit(
self,
exc_value=None,
exc_type=None,
exc_tb=None,
captureVars=False,
Failure__init__=Failure.__init__,
):
"""
Initialize failure object, possibly spawning pdb.
"""
if (exc_value, exc_type, exc_tb) == (None, None, None):
exc = sys.exc_info()
if not exc[0] == self.__class__ and DO_POST_MORTEM:
try:
strrepr = str(exc[1])
except BaseException:
strrepr = "broken str"
print(
"Jumping into debugger for post-mortem of exception '{}':".format(
strrepr
)
)
import pdb
pdb.post_mortem(exc[2])
Failure__init__(self, exc_value, exc_type, exc_tb, captureVars) |
Enable debug hooks for Failures. | def startDebugMode():
"""
Enable debug hooks for Failures.
"""
Failure.__init__ = _debuginit |
Compute a string usable as a new, temporary filename.
@param path: The path that the new temporary filename should be able to be
concatenated with.
@return: A pseudorandom, 16 byte string for use in secure filenames.
@rtype: the type of C{path} | def _secureEnoughString(path: AnyStr) -> AnyStr:
"""
Compute a string usable as a new, temporary filename.
@param path: The path that the new temporary filename should be able to be
concatenated with.
@return: A pseudorandom, 16 byte string for use in secure filenames.
@rtype: the type of C{path}
"""
secureishString = armor(randomBytes(16))[:16]
return _coerceToFilesystemEncoding(path, secureishString) |
Return C{path} as a string of L{bytes} suitable for use on this system's
filesystem.
@param path: The path to be made suitable.
@type path: L{bytes} or L{unicode}
@param encoding: The encoding to use if coercing to L{bytes}. If none is
given, L{sys.getfilesystemencoding} is used.
@return: L{bytes} | def _asFilesystemBytes(path: Union[bytes, str], encoding: Optional[str] = "") -> bytes:
"""
Return C{path} as a string of L{bytes} suitable for use on this system's
filesystem.
@param path: The path to be made suitable.
@type path: L{bytes} or L{unicode}
@param encoding: The encoding to use if coercing to L{bytes}. If none is
given, L{sys.getfilesystemencoding} is used.
@return: L{bytes}
"""
if isinstance(path, bytes):
return path
else:
if not encoding:
encoding = sys.getfilesystemencoding()
return path.encode(encoding, errors="surrogateescape") |
Return C{path} as a string of L{unicode} suitable for use on this system's
filesystem.
@param path: The path to be made suitable.
@type path: L{bytes} or L{unicode}
@param encoding: The encoding to use if coercing to L{unicode}. If none
is given, L{sys.getfilesystemencoding} is used.
@return: L{unicode} | def _asFilesystemText(path: Union[bytes, str], encoding: Optional[str] = None) -> str:
"""
Return C{path} as a string of L{unicode} suitable for use on this system's
filesystem.
@param path: The path to be made suitable.
@type path: L{bytes} or L{unicode}
@param encoding: The encoding to use if coercing to L{unicode}. If none
is given, L{sys.getfilesystemencoding} is used.
@return: L{unicode}
"""
if isinstance(path, str):
return path
else:
if encoding is None:
encoding = sys.getfilesystemencoding()
return path.decode(encoding, errors="surrogateescape") |
Return a C{newpath} that is suitable for joining to C{path}.
@param path: The path that it should be suitable for joining to.
@param newpath: The new portion of the path to be coerced if needed.
@param encoding: If coerced, the encoding that will be used. | def _coerceToFilesystemEncoding(
path: AnyStr, newpath: Union[bytes, str], encoding: Optional[str] = None
) -> AnyStr:
"""
Return a C{newpath} that is suitable for joining to C{path}.
@param path: The path that it should be suitable for joining to.
@param newpath: The new portion of the path to be coerced if needed.
@param encoding: If coerced, the encoding that will be used.
"""
if isinstance(path, bytes):
return _asFilesystemBytes(newpath, encoding=encoding)
else:
return _asFilesystemText(newpath, encoding=encoding) |
Determine if the lock of the given name is held or not.
@type name: C{str}
@param name: The filesystem path to the lock to test
@rtype: C{bool}
@return: True if the lock is held, False otherwise. | def isLocked(name):
"""
Determine if the lock of the given name is held or not.
@type name: C{str}
@param name: The filesystem path to the lock to test
@rtype: C{bool}
@return: True if the lock is held, False otherwise.
"""
l = FilesystemLock(name)
result = None
try:
result = l.lock()
finally:
if result:
l.unlock()
return not result |
Utility method which wraps a function in a try:/except:, logs a failure if
one occurs, and uses the system's logPrefix. | def callWithLogger(logger, func, *args, **kw):
"""
Utility method which wraps a function in a try:/except:, logs a failure if
one occurs, and uses the system's logPrefix.
"""
try:
lp = logger.logPrefix()
except KeyboardInterrupt:
raise
except BaseException:
lp = "(buggy logPrefix method)"
err(system=lp)
try:
return callWithContext({"system": lp}, func, *args, **kw)
except KeyboardInterrupt:
raise
except BaseException:
err(system=lp) |
Write a failure to the log.
The C{_stuff} and C{_why} parameters use an underscore prefix to lessen
the chance of colliding with a keyword argument the application wishes
to pass. It is intended that they be supplied with arguments passed
positionally, not by keyword.
@param _stuff: The failure to log. If C{_stuff} is L{None} a new
L{Failure} will be created from the current exception state. If
C{_stuff} is an C{Exception} instance it will be wrapped in a
L{Failure}.
@type _stuff: L{None}, C{Exception}, or L{Failure}.
@param _why: The source of this failure. This will be logged along with
C{_stuff} and should describe the context in which the failure
occurred.
@type _why: C{str} | def err(_stuff=None, _why=None, **kw):
"""
Write a failure to the log.
The C{_stuff} and C{_why} parameters use an underscore prefix to lessen
the chance of colliding with a keyword argument the application wishes
to pass. It is intended that they be supplied with arguments passed
positionally, not by keyword.
@param _stuff: The failure to log. If C{_stuff} is L{None} a new
L{Failure} will be created from the current exception state. If
C{_stuff} is an C{Exception} instance it will be wrapped in a
L{Failure}.
@type _stuff: L{None}, C{Exception}, or L{Failure}.
@param _why: The source of this failure. This will be logged along with
C{_stuff} and should describe the context in which the failure
occurred.
@type _why: C{str}
"""
if _stuff is None:
_stuff = failure.Failure()
if isinstance(_stuff, failure.Failure):
msg(failure=_stuff, why=_why, isError=1, **kw)
elif isinstance(_stuff, Exception):
msg(failure=failure.Failure(_stuff), why=_why, isError=1, **kw)
else:
msg(repr(_stuff), why=_why, isError=1, **kw) |
Try to format a string, swallowing all errors to always return a string.
@note: For backward-compatibility reasons, this function ensures that it
returns a native string, meaning L{bytes} in Python 2 and L{str} in
Python 3.
@param fmtString: a C{%}-format string
@param fmtDict: string formatting arguments for C{fmtString}
@return: A native string, formatted from C{fmtString} and C{fmtDict}. | def _safeFormat(fmtString: str, fmtDict: Dict[str, Any]) -> str:
"""
Try to format a string, swallowing all errors to always return a string.
@note: For backward-compatibility reasons, this function ensures that it
returns a native string, meaning L{bytes} in Python 2 and L{str} in
Python 3.
@param fmtString: a C{%}-format string
@param fmtDict: string formatting arguments for C{fmtString}
@return: A native string, formatted from C{fmtString} and C{fmtDict}.
"""
# There's a way we could make this if not safer at least more
# informative: perhaps some sort of str/repr wrapper objects
# could be wrapped around the things inside of C{fmtDict}. That way
# if the event dict contains an object with a bad __repr__, we
# can only cry about that individual object instead of the
# entire event dict.
try:
text = fmtString % fmtDict
except KeyboardInterrupt:
raise
except BaseException:
try:
text = (
"Invalid format string or unformattable object in "
"log message: %r, %s" % (fmtString, fmtDict)
)
except BaseException:
try:
text = (
"UNFORMATTABLE OBJECT WRITTEN TO LOG with fmt %r, "
"MESSAGE LOST" % (fmtString,)
)
except BaseException:
text = (
"PATHOLOGICAL ERROR IN BOTH FORMAT STRING AND "
"MESSAGE DETAILS, MESSAGE LOST"
)
return text |
Extract text from an event dict passed to a log observer. If it cannot
handle the dict, it returns None.
The possible keys of eventDict are:
- C{message}: by default, it holds the final text. It's required, but can
be empty if either C{isError} or C{format} is provided (the first
having the priority).
- C{isError}: boolean indicating the nature of the event.
- C{failure}: L{failure.Failure} instance, required if the event is an
error.
- C{why}: if defined, used as header of the traceback in case of errors.
- C{format}: string format used in place of C{message} to customize
the event. It uses all keys present in C{eventDict} to format
the text.
Other keys will be used when applying the C{format}, or ignored. | def textFromEventDict(eventDict: EventDict) -> Optional[str]:
"""
Extract text from an event dict passed to a log observer. If it cannot
handle the dict, it returns None.
The possible keys of eventDict are:
- C{message}: by default, it holds the final text. It's required, but can
be empty if either C{isError} or C{format} is provided (the first
having the priority).
- C{isError}: boolean indicating the nature of the event.
- C{failure}: L{failure.Failure} instance, required if the event is an
error.
- C{why}: if defined, used as header of the traceback in case of errors.
- C{format}: string format used in place of C{message} to customize
the event. It uses all keys present in C{eventDict} to format
the text.
Other keys will be used when applying the C{format}, or ignored.
"""
edm = eventDict["message"]
if not edm:
if eventDict["isError"] and "failure" in eventDict:
why = cast(str, eventDict.get("why"))
if why:
why = reflect.safe_str(why)
else:
why = "Unhandled Error"
try:
traceback = cast(failure.Failure, eventDict["failure"]).getTraceback()
except Exception as e:
traceback = "(unable to obtain traceback): " + str(e)
text = why + "\n" + traceback
elif "format" in eventDict:
text = _safeFormat(eventDict["format"], eventDict)
else:
# We don't know how to log this
return None
else:
text = " ".join(map(reflect.safe_str, edm))
return text |
Initialize logging to a specified file.
@return: A L{FileLogObserver} if a new observer is added, None otherwise. | def startLogging(file, *a, **kw):
"""
Initialize logging to a specified file.
@return: A L{FileLogObserver} if a new observer is added, None otherwise.
"""
if isinstance(file, LoggingFile):
return
flo = FileLogObserver(file)
startLoggingWithObserver(flo.emit, *a, **kw)
return flo |
Initialize logging to a specified observer. If setStdout is true
(defaults to yes), also redirect sys.stdout and sys.stderr
to the specified file. | def startLoggingWithObserver(observer, setStdout=1):
"""
Initialize logging to a specified observer. If setStdout is true
(defaults to yes), also redirect sys.stdout and sys.stderr
to the specified file.
"""
theLogPublisher._startLogging(observer, setStdout)
msg("Log opened.") |
Discard messages logged via the global C{logfile} object. | def discardLogs():
"""
Discard messages logged via the global C{logfile} object.
"""
global logfile
logfile = NullFile() |
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 | 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 |
Provide the default behavior of PythonPath's sys.path factory, which is to
return the current value of sys.path.
@return: L{sys.path} | 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 |
Deeply iterate all modules on the global python path.
@param importPackages: Import packages as they are seen. | def walkModules(importPackages=False):
"""
Deeply iterate all modules on the global python path.
@param importPackages: Import packages as they are seen.
"""
return theSystemPath.walkModules(importPackages=importPackages) |
Iterate all modules and top-level packages on the global Python path, but
do not descend into packages. | def iterModules():
"""
Iterate all modules and top-level packages on the global Python path, but
do not descend into packages.
"""
return theSystemPath.iterModules() |
Retrieve a module from the system path. | def getModule(moduleName):
"""
Retrieve a module from the system path.
"""
return theSystemPath[moduleName] |
Search PATH for executable files with the given name.
On newer versions of MS-Windows, the PATHEXT environment variable will be
set to the list of file extensions for files considered executable. This
will normally include things like ".EXE". This function will also find files
with the given name ending with any of these extensions.
On MS-Windows the only flag that has any meaning is os.F_OK. Any other
flags will be ignored.
@type name: C{str}
@param name: The name for which to search.
@type flags: C{int}
@param flags: Arguments to L{os.access}.
@rtype: C{list}
@return: A list of the full paths to files found, in the order in which they
were found. | def which(name, flags=os.X_OK):
"""
Search PATH for executable files with the given name.
On newer versions of MS-Windows, the PATHEXT environment variable will be
set to the list of file extensions for files considered executable. This
will normally include things like ".EXE". This function will also find files
with the given name ending with any of these extensions.
On MS-Windows the only flag that has any meaning is os.F_OK. Any other
flags will be ignored.
@type name: C{str}
@param name: The name for which to search.
@type flags: C{int}
@param flags: Arguments to L{os.access}.
@rtype: C{list}
@return: A list of the full paths to files found, in the order in which they
were found.
"""
result = []
exts = list(filter(None, os.environ.get("PATHEXT", "").split(os.pathsep)))
path = os.environ.get("PATH", None)
if path is None:
return []
for p in os.environ.get("PATH", "").split(os.pathsep):
p = os.path.join(p, name)
if os.access(p, flags):
result.append(p)
for e in exts:
pext = p + e
if os.access(pext, flags):
result.append(pext)
return result |
Get the latest version of a function. | def latestFunction(oldFunc):
"""
Get the latest version of a function.
"""
# This may be CPython specific, since I believe jython instantiates a new
# module upon reload.
dictID = id(oldFunc.__globals__)
module = _modDictIDMap.get(dictID)
if module is None:
return oldFunc
return getattr(module, oldFunc.__name__) |
Get the latest version of a class. | def latestClass(oldClass):
"""
Get the latest version of a class.
"""
module = reflect.namedModule(oldClass.__module__)
newClass = getattr(module, oldClass.__name__)
newBases = [latestClass(base) for base in newClass.__bases__]
if newClass.__module__ == "builtins":
# builtin members can't be reloaded sanely
return newClass
try:
# This makes old-style stuff work
newClass.__bases__ = tuple(newBases)
return newClass
except TypeError:
ctor = type(newClass)
return ctor(newClass.__name__, tuple(newBases), dict(newClass.__dict__)) |
Updates an instance to be current. | def updateInstance(self):
"""
Updates an instance to be current.
"""
self.__class__ = latestClass(self.__class__) |
A getattr method to cause a class to be refreshed. | def __injectedgetattr__(self, name):
"""
A getattr method to cause a class to be refreshed.
"""
if name == "__del__":
raise AttributeError("Without this, Python segfaults.")
updateInstance(self)
log.msg(f"(rebuilding stale {reflect.qual(self.__class__)} instance ({name}))")
result = getattr(self, name)
return result |
Reload a module and do as much as possible to replace its references. | def rebuild(module, doLog=1):
"""
Reload a module and do as much as possible to replace its references.
"""
global lastRebuild
lastRebuild = time.time()
if hasattr(module, "ALLOW_TWISTED_REBUILD"):
# Is this module allowed to be rebuilt?
if not module.ALLOW_TWISTED_REBUILD:
raise RuntimeError("I am not allowed to be rebuilt.")
if doLog:
log.msg(f"Rebuilding {str(module.__name__)}...")
# Safely handle adapter re-registration
from twisted.python import components
components.ALLOW_DUPLICATES = True
d = module.__dict__
_modDictIDMap[id(d)] = module
newclasses = {}
classes = {}
functions = {}
values = {}
if doLog:
log.msg(f" (scanning {str(module.__name__)}): ")
for k, v in d.items():
if issubclass(type(v), types.FunctionType):
if v.__globals__ is module.__dict__:
functions[v] = 1
if doLog:
log.logfile.write("f")
log.logfile.flush()
elif isinstance(v, type):
if v.__module__ == module.__name__:
newclasses[v] = 1
if doLog:
log.logfile.write("o")
log.logfile.flush()
values.update(classes)
values.update(functions)
fromOldModule = values.__contains__
newclasses = newclasses.keys()
classes = classes.keys()
functions = functions.keys()
if doLog:
log.msg("")
log.msg(f" (reload {str(module.__name__)})")
# Boom.
reload(module)
# Make sure that my traceback printing will at least be recent...
linecache.clearcache()
if doLog:
log.msg(f" (cleaning {str(module.__name__)}): ")
for clazz in classes:
if getattr(module, clazz.__name__) is clazz:
log.msg(f"WARNING: class {reflect.qual(clazz)} not replaced by reload!")
else:
if doLog:
log.logfile.write("x")
log.logfile.flush()
clazz.__bases__ = ()
clazz.__dict__.clear()
clazz.__getattr__ = __injectedgetattr__
clazz.__module__ = module.__name__
if newclasses:
import gc
for nclass in newclasses:
ga = getattr(module, nclass.__name__)
if ga is nclass:
log.msg(
"WARNING: new-class {} not replaced by reload!".format(
reflect.qual(nclass)
)
)
else:
for r in gc.get_referrers(nclass):
if getattr(r, "__class__", None) is nclass:
r.__class__ = ga
if doLog:
log.msg("")
log.msg(f" (fixing {str(module.__name__)}): ")
modcount = 0
for mk, mod in sys.modules.items():
modcount = modcount + 1
if mod == module or mod is None:
continue
if not hasattr(mod, "__file__"):
# It's a builtin module; nothing to replace here.
continue
if hasattr(mod, "__bundle__"):
# PyObjC has a few buggy objects which segfault if you hash() them.
# It doesn't make sense to try rebuilding extension modules like
# this anyway, so don't try.
continue
changed = 0
for k, v in mod.__dict__.items():
try:
hash(v)
except Exception:
continue
if fromOldModule(v):
if doLog:
log.logfile.write("f")
log.logfile.flush()
nv = latestFunction(v)
changed = 1
setattr(mod, k, nv)
if doLog and not changed and ((modcount % 10) == 0):
log.logfile.write(".")
log.logfile.flush()
components.ALLOW_DUPLICATES = False
if doLog:
log.msg("")
log.msg(f" Rebuilt {str(module.__name__)}.")
return module |
Given a class object C{classObj}, returns a list of method names that match
the string C{prefix}.
@param classObj: A class object from which to collect method names.
@param prefix: A native string giving a prefix. Each method with a name
which begins with this prefix will be returned.
@type prefix: L{str}
@return: A list of the names of matching methods of C{classObj} (and base
classes of C{classObj}).
@rtype: L{list} of L{str} | def prefixedMethodNames(classObj, prefix):
"""
Given a class object C{classObj}, returns a list of method names that match
the string C{prefix}.
@param classObj: A class object from which to collect method names.
@param prefix: A native string giving a prefix. Each method with a name
which begins with this prefix will be returned.
@type prefix: L{str}
@return: A list of the names of matching methods of C{classObj} (and base
classes of C{classObj}).
@rtype: L{list} of L{str}
"""
dct = {}
addMethodNamesToDict(classObj, dct, prefix)
return list(dct.keys()) |
This goes through C{classObj} (and its bases) and puts method names
starting with 'prefix' in 'dict' with a value of 1. if baseClass isn't
None, methods will only be added if classObj is-a baseClass
If the class in question has the methods 'prefix_methodname' and
'prefix_methodname2', the resulting dict should look something like:
{"methodname": 1, "methodname2": 1}.
@param classObj: A class object from which to collect method names.
@param dict: A L{dict} which will be updated with the results of the
accumulation. Items are added to this dictionary, with method names as
keys and C{1} as values.
@type dict: L{dict}
@param prefix: A native string giving a prefix. Each method of C{classObj}
(and base classes of C{classObj}) with a name which begins with this
prefix will be returned.
@type prefix: L{str}
@param baseClass: A class object at which to stop searching upwards for new
methods. To collect all method names, do not pass a value for this
parameter.
@return: L{None} | def addMethodNamesToDict(classObj, dict, prefix, baseClass=None):
"""
This goes through C{classObj} (and its bases) and puts method names
starting with 'prefix' in 'dict' with a value of 1. if baseClass isn't
None, methods will only be added if classObj is-a baseClass
If the class in question has the methods 'prefix_methodname' and
'prefix_methodname2', the resulting dict should look something like:
{"methodname": 1, "methodname2": 1}.
@param classObj: A class object from which to collect method names.
@param dict: A L{dict} which will be updated with the results of the
accumulation. Items are added to this dictionary, with method names as
keys and C{1} as values.
@type dict: L{dict}
@param prefix: A native string giving a prefix. Each method of C{classObj}
(and base classes of C{classObj}) with a name which begins with this
prefix will be returned.
@type prefix: L{str}
@param baseClass: A class object at which to stop searching upwards for new
methods. To collect all method names, do not pass a value for this
parameter.
@return: L{None}
"""
for base in classObj.__bases__:
addMethodNamesToDict(base, dict, prefix, baseClass)
if baseClass is None or baseClass in classObj.__bases__:
for name, method in classObj.__dict__.items():
optName = name[len(prefix) :]
if (
(type(method) is types.FunctionType)
and (name[: len(prefix)] == prefix)
and (len(optName))
):
dict[optName] = 1 |
Given an object C{obj}, returns a list of method objects that match the
string C{prefix}.
@param obj: An arbitrary object from which to collect methods.
@param prefix: A native string giving a prefix. Each method of C{obj} with
a name which begins with this prefix will be returned.
@type prefix: L{str}
@return: A list of the matching method objects.
@rtype: L{list} | def prefixedMethods(obj, prefix=""):
"""
Given an object C{obj}, returns a list of method objects that match the
string C{prefix}.
@param obj: An arbitrary object from which to collect methods.
@param prefix: A native string giving a prefix. Each method of C{obj} with
a name which begins with this prefix will be returned.
@type prefix: L{str}
@return: A list of the matching method objects.
@rtype: L{list}
"""
dct = {}
accumulateMethods(obj, dct, prefix)
return list(dct.values()) |
Given an object C{obj}, add all methods that begin with C{prefix}.
@param obj: An arbitrary object to collect methods from.
@param dict: A L{dict} which will be updated with the results of the
accumulation. Items are added to this dictionary, with method names as
keys and corresponding instance method objects as values.
@type dict: L{dict}
@param prefix: A native string giving a prefix. Each method of C{obj} with
a name which begins with this prefix will be returned.
@type prefix: L{str}
@param curClass: The class in the inheritance hierarchy at which to start
collecting methods. Collection proceeds up. To collect all methods
from C{obj}, do not pass a value for this parameter.
@return: L{None} | def accumulateMethods(obj, dict, prefix="", curClass=None):
"""
Given an object C{obj}, add all methods that begin with C{prefix}.
@param obj: An arbitrary object to collect methods from.
@param dict: A L{dict} which will be updated with the results of the
accumulation. Items are added to this dictionary, with method names as
keys and corresponding instance method objects as values.
@type dict: L{dict}
@param prefix: A native string giving a prefix. Each method of C{obj} with
a name which begins with this prefix will be returned.
@type prefix: L{str}
@param curClass: The class in the inheritance hierarchy at which to start
collecting methods. Collection proceeds up. To collect all methods
from C{obj}, do not pass a value for this parameter.
@return: L{None}
"""
if not curClass:
curClass = obj.__class__
for base in curClass.__bases__:
# The implementation of the object class is different on PyPy vs.
# CPython. This has the side effect of making accumulateMethods()
# pick up object methods from all new-style classes -
# such as __getattribute__, etc.
# If we ignore 'object' when accumulating methods, we can get
# consistent behavior on Pypy and CPython.
if base is not object:
accumulateMethods(obj, dict, prefix, base)
for name, method in curClass.__dict__.items():
optName = name[len(prefix) :]
if (
(type(method) is types.FunctionType)
and (name[: len(prefix)] == prefix)
and (len(optName))
):
dict[optName] = getattr(obj, name) |
Return a module given its name. | def namedModule(name):
"""
Return a module given its name.
"""
topLevel = __import__(name)
packages = name.split(".")[1:]
m = topLevel
for p in packages:
m = getattr(m, p)
return m |
Get a fully named module-global object. | def namedObject(name):
"""
Get a fully named module-global object.
"""
classSplit = name.split(".")
module = namedModule(".".join(classSplit[:-1]))
return getattr(module, classSplit[-1]) |
Try to import a module given its name, returning C{default} value if
C{ImportError} is raised during import.
@param name: Module name as it would have been passed to C{import}.
@type name: C{str}.
@param default: Value returned in case C{ImportError} is raised while
importing the module.
@return: Module or default value. | def requireModule(name, default=None):
"""
Try to import a module given its name, returning C{default} value if
C{ImportError} is raised during import.
@param name: Module name as it would have been passed to C{import}.
@type name: C{str}.
@param default: Value returned in case C{ImportError} is raised while
importing the module.
@return: Module or default value.
"""
try:
return namedModule(name)
except ImportError:
return default |
Import the given name as a module, then walk the stack to determine whether
the failure was the module not existing, or some code in the module (for
example a dependent import) failing. This can be helpful to determine
whether any actual application code was run. For example, to distiguish
administrative error (entering the wrong module name), from programmer
error (writing buggy code in a module that fails to import).
@param importName: The name of the module to import.
@type importName: C{str}
@raise Exception: if something bad happens. This can be any type of
exception, since nobody knows what loading some arbitrary code might
do.
@raise _NoModuleFound: if no module was found. | def _importAndCheckStack(importName):
"""
Import the given name as a module, then walk the stack to determine whether
the failure was the module not existing, or some code in the module (for
example a dependent import) failing. This can be helpful to determine
whether any actual application code was run. For example, to distiguish
administrative error (entering the wrong module name), from programmer
error (writing buggy code in a module that fails to import).
@param importName: The name of the module to import.
@type importName: C{str}
@raise Exception: if something bad happens. This can be any type of
exception, since nobody knows what loading some arbitrary code might
do.
@raise _NoModuleFound: if no module was found.
"""
try:
return __import__(importName)
except ImportError:
excType, excValue, excTraceback = sys.exc_info()
while excTraceback:
execName = excTraceback.tb_frame.f_globals["__name__"]
if execName == importName:
raise excValue.with_traceback(excTraceback)
excTraceback = excTraceback.tb_next
raise _NoModuleFound() |
Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specified by all of the
name which came before it. For example, the fully-qualified name of this
object is 'twisted.python.reflect.namedAny'.
@type name: L{str}
@param name: The name of the object to return.
@raise InvalidName: If the name is an empty string, starts or ends with
a '.', or is otherwise syntactically incorrect.
@raise ModuleNotFound: If the name is syntactically correct but the
module it specifies cannot be imported because it does not appear to
exist.
@raise ObjectNotFound: If the name is syntactically correct, includes at
least one '.', but the module it specifies cannot be imported because
it does not appear to exist.
@raise AttributeError: If an attribute of an object along the way cannot be
accessed, or a module along the way is not found.
@return: the Python object identified by 'name'. | def namedAny(name):
"""
Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specified by all of the
name which came before it. For example, the fully-qualified name of this
object is 'twisted.python.reflect.namedAny'.
@type name: L{str}
@param name: The name of the object to return.
@raise InvalidName: If the name is an empty string, starts or ends with
a '.', or is otherwise syntactically incorrect.
@raise ModuleNotFound: If the name is syntactically correct but the
module it specifies cannot be imported because it does not appear to
exist.
@raise ObjectNotFound: If the name is syntactically correct, includes at
least one '.', but the module it specifies cannot be imported because
it does not appear to exist.
@raise AttributeError: If an attribute of an object along the way cannot be
accessed, or a module along the way is not found.
@return: the Python object identified by 'name'.
"""
if not name:
raise InvalidName("Empty module name")
names = name.split(".")
# if the name starts or ends with a '.' or contains '..', the __import__
# will raise an 'Empty module name' error. This will provide a better error
# message.
if "" in names:
raise InvalidName(
"name must be a string giving a '.'-separated list of Python "
"identifiers, not %r" % (name,)
)
topLevelPackage = None
moduleNames = names[:]
while not topLevelPackage:
if moduleNames:
trialname = ".".join(moduleNames)
try:
topLevelPackage = _importAndCheckStack(trialname)
except _NoModuleFound:
moduleNames.pop()
else:
if len(names) == 1:
raise ModuleNotFound(f"No module named {name!r}")
else:
raise ObjectNotFound(f"{name!r} does not name an object")
obj = topLevelPackage
for n in names[1:]:
obj = getattr(obj, n)
return obj |
Convert a name in the filesystem to the name of the Python module it is.
This is aggressive about getting a module name back from a file; it will
always return a string. Aggressive means 'sometimes wrong'; it won't look
at the Python path or try to do any error checking: don't use this method
unless you already know that the filename you're talking about is a Python
module.
@param fn: A filesystem path to a module or package; C{bytes} on Python 2,
C{bytes} or C{unicode} on Python 3.
@return: A hopefully importable module name.
@rtype: C{str} | def filenameToModuleName(fn):
"""
Convert a name in the filesystem to the name of the Python module it is.
This is aggressive about getting a module name back from a file; it will
always return a string. Aggressive means 'sometimes wrong'; it won't look
at the Python path or try to do any error checking: don't use this method
unless you already know that the filename you're talking about is a Python
module.
@param fn: A filesystem path to a module or package; C{bytes} on Python 2,
C{bytes} or C{unicode} on Python 3.
@return: A hopefully importable module name.
@rtype: C{str}
"""
if isinstance(fn, bytes):
initPy = b"__init__.py"
else:
initPy = "__init__.py"
fullName = os.path.abspath(fn)
base = os.path.basename(fn)
if not base:
# this happens when fn ends with a path separator, just skit it
base = os.path.basename(fn[:-1])
modName = nativeString(os.path.splitext(base)[0])
while 1:
fullName = os.path.dirname(fullName)
if os.path.exists(os.path.join(fullName, initPy)):
modName = "{}.{}".format(
nativeString(os.path.basename(fullName)),
nativeString(modName),
)
else:
break
return modName |
Return full import path of a class. | def qual(clazz: Type[object]) -> str:
"""
Return full import path of a class.
"""
return clazz.__module__ + "." + clazz.__name__ |
Helper function for L{safe_repr} and L{safe_str}.
Called when C{repr} or C{str} fail. Returns a string containing info about
C{o} and the latest exception.
@param formatter: C{str} or C{repr}.
@type formatter: C{type}
@param o: Any object.
@rtype: C{str}
@return: A string containing information about C{o} and the raised
exception. | def _safeFormat(formatter: Union[types.FunctionType, Type[str]], o: object) -> str:
"""
Helper function for L{safe_repr} and L{safe_str}.
Called when C{repr} or C{str} fail. Returns a string containing info about
C{o} and the latest exception.
@param formatter: C{str} or C{repr}.
@type formatter: C{type}
@param o: Any object.
@rtype: C{str}
@return: A string containing information about C{o} and the raised
exception.
"""
io = StringIO()
traceback.print_exc(file=io)
className = _determineClassName(o)
tbValue = io.getvalue()
return "<{} instance at 0x{:x} with {} error:\n {}>".format(
className,
id(o),
formatter.__name__,
tbValue,
) |
Returns a string representation of an object, or a string containing a
traceback, if that object's __repr__ raised an exception.
@param o: Any object.
@rtype: C{str} | def safe_repr(o):
"""
Returns a string representation of an object, or a string containing a
traceback, if that object's __repr__ raised an exception.
@param o: Any object.
@rtype: C{str}
"""
try:
return repr(o)
except BaseException:
return _safeFormat(repr, o) |
Returns a string representation of an object, or a string containing a
traceback, if that object's __str__ raised an exception.
@param o: Any object. | def safe_str(o: object) -> str:
"""
Returns a string representation of an object, or a string containing a
traceback, if that object's __str__ raised an exception.
@param o: Any object.
"""
if isinstance(o, bytes):
# If o is bytes and seems to holds a utf-8 encoded string,
# convert it to str.
try:
return o.decode("utf-8")
except BaseException:
pass
try:
return str(o)
except BaseException:
return _safeFormat(str, o) |
Return the class or type of object 'obj'. | def getClass(obj):
"""
Return the class or type of object 'obj'.
"""
return type(obj) |
Accumulate all attributes of a given name in a class hierarchy into a single dictionary.
Assuming all class attributes of this name are dictionaries.
If any of the dictionaries being accumulated have the same key, the
one highest in the class hierarchy wins.
(XXX: If "highest" means "closest to the starting class".)
Ex::
class Soy:
properties = {"taste": "bland"}
class Plant:
properties = {"colour": "green"}
class Seaweed(Plant):
pass
class Lunch(Soy, Seaweed):
properties = {"vegan": 1 }
dct = {}
accumulateClassDict(Lunch, "properties", dct)
print(dct)
{"taste": "bland", "colour": "green", "vegan": 1} | def accumulateClassDict(classObj, attr, adict, baseClass=None):
"""
Accumulate all attributes of a given name in a class hierarchy into a single dictionary.
Assuming all class attributes of this name are dictionaries.
If any of the dictionaries being accumulated have the same key, the
one highest in the class hierarchy wins.
(XXX: If \"highest\" means \"closest to the starting class\".)
Ex::
class Soy:
properties = {\"taste\": \"bland\"}
class Plant:
properties = {\"colour\": \"green\"}
class Seaweed(Plant):
pass
class Lunch(Soy, Seaweed):
properties = {\"vegan\": 1 }
dct = {}
accumulateClassDict(Lunch, \"properties\", dct)
print(dct)
{\"taste\": \"bland\", \"colour\": \"green\", \"vegan\": 1}
"""
for base in classObj.__bases__:
accumulateClassDict(base, attr, adict)
if baseClass is None or baseClass in classObj.__bases__:
adict.update(classObj.__dict__.get(attr, {})) |
Accumulate all attributes of a given name in a class hierarchy into a single list.
Assuming all class attributes of this name are lists. | def accumulateClassList(classObj, attr, listObj, baseClass=None):
"""
Accumulate all attributes of a given name in a class hierarchy into a single list.
Assuming all class attributes of this name are lists.
"""
for base in classObj.__bases__:
accumulateClassList(base, attr, listObj)
if baseClass is None or baseClass in classObj.__bases__:
listObj.extend(classObj.__dict__.get(attr, [])) |
L{objgrep} finds paths between C{start} and C{goal}.
Starting at the python object C{start}, we will loop over every reachable
reference, tring to find the python object C{goal} (i.e. every object
C{candidate} for whom C{eq(candidate, goal)} is truthy), and return a
L{list} of L{str}, where each L{str} is Python syntax for a path between
C{start} and C{goal}.
Since this can be slightly difficult to visualize, here's an example::
>>> class Holder:
... def __init__(self, x):
... self.x = x
...
>>> start = Holder({"irrelevant": "ignore",
... "relevant": [7, 1, 3, 5, 7]})
>>> for path in objgrep(start, 7):
... print("start" + path)
start.x['relevant'][0]
start.x['relevant'][4]
This can be useful, for example, when debugging stateful graphs of objects
attached to a socket, trying to figure out where a particular connection is
attached.
@param start: The object to start looking at.
@param goal: The object to search for.
@param eq: A 2-argument predicate which takes an object found by traversing
references starting at C{start}, as well as C{goal}, and returns a
boolean.
@param path: The prefix of the path to include in every return value; empty
by default.
@param paths: The result object to append values to; a list of strings.
@param seen: A dictionary mapping ints (object IDs) to objects already
seen.
@param showUnknowns: if true, print a message to C{stdout} when
encountering objects that C{objgrep} does not know how to traverse.
@param maxDepth: The maximum number of object references to attempt
traversing before giving up. If an integer, limit to that many links,
if C{None}, unlimited.
@return: A list of strings representing python object paths starting at
C{start} and terminating at C{goal}. | def objgrep(
start,
goal,
eq=isLike,
path="",
paths=None,
seen=None,
showUnknowns=0,
maxDepth=None,
):
"""
L{objgrep} finds paths between C{start} and C{goal}.
Starting at the python object C{start}, we will loop over every reachable
reference, tring to find the python object C{goal} (i.e. every object
C{candidate} for whom C{eq(candidate, goal)} is truthy), and return a
L{list} of L{str}, where each L{str} is Python syntax for a path between
C{start} and C{goal}.
Since this can be slightly difficult to visualize, here's an example::
>>> class Holder:
... def __init__(self, x):
... self.x = x
...
>>> start = Holder({"irrelevant": "ignore",
... "relevant": [7, 1, 3, 5, 7]})
>>> for path in objgrep(start, 7):
... print("start" + path)
start.x['relevant'][0]
start.x['relevant'][4]
This can be useful, for example, when debugging stateful graphs of objects
attached to a socket, trying to figure out where a particular connection is
attached.
@param start: The object to start looking at.
@param goal: The object to search for.
@param eq: A 2-argument predicate which takes an object found by traversing
references starting at C{start}, as well as C{goal}, and returns a
boolean.
@param path: The prefix of the path to include in every return value; empty
by default.
@param paths: The result object to append values to; a list of strings.
@param seen: A dictionary mapping ints (object IDs) to objects already
seen.
@param showUnknowns: if true, print a message to C{stdout} when
encountering objects that C{objgrep} does not know how to traverse.
@param maxDepth: The maximum number of object references to attempt
traversing before giving up. If an integer, limit to that many links,
if C{None}, unlimited.
@return: A list of strings representing python object paths starting at
C{start} and terminating at C{goal}.
"""
if paths is None:
paths = []
if seen is None:
seen = {}
if eq(start, goal):
paths.append(path)
if id(start) in seen:
if seen[id(start)] is start:
return
if maxDepth is not None:
if maxDepth == 0:
return
maxDepth -= 1
seen[id(start)] = start
# Make an alias for those arguments which are passed recursively to
# objgrep for container objects.
args = (paths, seen, showUnknowns, maxDepth)
if isinstance(start, dict):
for k, v in start.items():
objgrep(k, goal, eq, path + "{" + repr(v) + "}", *args)
objgrep(v, goal, eq, path + "[" + repr(k) + "]", *args)
elif isinstance(start, (list, tuple, deque)):
for idx, _elem in enumerate(start):
objgrep(start[idx], goal, eq, path + "[" + str(idx) + "]", *args)
elif isinstance(start, types.MethodType):
objgrep(start.__self__, goal, eq, path + ".__self__", *args)
objgrep(start.__func__, goal, eq, path + ".__func__", *args)
objgrep(start.__self__.__class__, goal, eq, path + ".__self__.__class__", *args)
elif hasattr(start, "__dict__"):
for k, v in start.__dict__.items():
objgrep(v, goal, eq, path + "." + k, *args)
elif isinstance(start, weakref.ReferenceType):
objgrep(start(), goal, eq, path + "()", *args)
elif isinstance(
start,
(
str,
int,
types.FunctionType,
types.BuiltinMethodType,
RegexType,
float,
type(None),
IOBase,
),
) or type(start).__name__ in (
"wrapper_descriptor",
"method_descriptor",
"member_descriptor",
"getset_descriptor",
):
pass
elif showUnknowns:
print("unknown type", type(start), start)
return paths |
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)}. | 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 input("run ?? ").startswith("n"):
return
if null:
command = "%s > /dev/null" % command
if os.system(command) != 0:
raise CommandFailed(command) |
Returns the Python version as a dot-separated string. | def shortPythonVersion() -> str:
"""
Returns the Python version as a dot-separated string.
"""
return "%s.%s.%s" % sys.version_info[:3] |
Send a message on a socket.
@param socket: The socket to send the message on.
@param data: Bytes to write to the socket.
@param ancillary: Extra data to send over the socket outside of the normal
datagram or stream mechanism. By default no ancillary data is sent.
@param flags: Flags to affect how the message is sent. See the C{MSG_}
constants in the sendmsg(2) manual page. By default no flags are set.
@return: The return value of the underlying syscall, if it succeeds. | def sendmsg(
socket: Socket,
data: bytes,
ancillary: List[Tuple[int, int, bytes]] = [],
flags: int = 0,
) -> int:
"""
Send a message on a socket.
@param socket: The socket to send the message on.
@param data: Bytes to write to the socket.
@param ancillary: Extra data to send over the socket outside of the normal
datagram or stream mechanism. By default no ancillary data is sent.
@param flags: Flags to affect how the message is sent. See the C{MSG_}
constants in the sendmsg(2) manual page. By default no flags are set.
@return: The return value of the underlying syscall, if it succeeds.
"""
return socket.sendmsg([data], ancillary, flags) |
Receive a message on a socket.
@param socket: The socket to receive the message on.
@param maxSize: The maximum number of bytes to receive from the socket using
the datagram or stream mechanism. The default maximum is 8192.
@param cmsgSize: The maximum number of bytes to receive from the socket
outside of the normal datagram or stream mechanism. The default maximum
is 4096.
@param flags: Flags to affect how the message is sent. See the C{MSG_}
constants in the sendmsg(2) manual page. By default no flags are set.
@return: A named 3-tuple of the bytes received using the datagram/stream
mechanism, a L{list} of L{tuple}s giving ancillary received data, and
flags as an L{int} describing the data received. | def recvmsg(
socket: Socket, maxSize: int = 8192, cmsgSize: int = 4096, flags: int = 0
) -> ReceivedMessage:
"""
Receive a message on a socket.
@param socket: The socket to receive the message on.
@param maxSize: The maximum number of bytes to receive from the socket using
the datagram or stream mechanism. The default maximum is 8192.
@param cmsgSize: The maximum number of bytes to receive from the socket
outside of the normal datagram or stream mechanism. The default maximum
is 4096.
@param flags: Flags to affect how the message is sent. See the C{MSG_}
constants in the sendmsg(2) manual page. By default no flags are set.
@return: A named 3-tuple of the bytes received using the datagram/stream
mechanism, a L{list} of L{tuple}s giving ancillary received data, and
flags as an L{int} describing the data received.
"""
# In Twisted's _sendmsg.c, the csmg_space was defined as:
# int cmsg_size = 4096;
# cmsg_space = CMSG_SPACE(cmsg_size);
# Since the default in Python 3's socket is 0, we need to define our
# own default of 4096. -hawkie
data, ancillary, flags = socket.recvmsg(maxSize, CMSG_SPACE(cmsgSize), flags)[0:3]
return ReceivedMessage(data=data, ancillary=ancillary, flags=flags) |
Return the family of the given socket.
@param socket: The socket to get the family of. | def getSocketFamily(socket: Socket) -> int:
"""
Return the family of the given socket.
@param socket: The socket to get the family of.
"""
return socket.family |
Open an existing shortcut for reading.
@return: The shortcut object
@rtype: Shortcut | def open(filename):
"""
Open an existing shortcut for reading.
@return: The shortcut object
@rtype: Shortcut
"""
sc = Shortcut()
sc.load(filename)
return sc |
Send all Twisted logging output to syslog from now on.
The prefix, options and facility arguments are passed to
C{syslog.openlog()}, see the Python syslog documentation for details. For
other parameters, see L{twisted.python.log.startLoggingWithObserver}. | def startLogging(
prefix="Twisted", options=DEFAULT_OPTIONS, facility=DEFAULT_FACILITY, setStdout=1
):
"""
Send all Twisted logging output to syslog from now on.
The prefix, options and facility arguments are passed to
C{syslog.openlog()}, see the Python syslog documentation for details. For
other parameters, see L{twisted.python.log.startLoggingWithObserver}.
"""
obs = SyslogObserver(prefix, options, facility)
log.startLoggingWithObserver(obs.emit, setStdout=setStdout) |
Parse the I{LISTEN_FDS} environment variable supplied by systemd.
@param start: systemd provides only a count of the number of descriptors
that have been inherited. This is the integer value of the first
inherited descriptor. Subsequent inherited descriptors are numbered
counting up from here. See L{ListenFDs._START}.
@param environ: The environment variable mapping in which to look for the
value to parse.
@return: The integer values of the inherited file descriptors, in order. | def _parseDescriptors(start: int, environ: Mapping[str, str]) -> List[int]:
"""
Parse the I{LISTEN_FDS} environment variable supplied by systemd.
@param start: systemd provides only a count of the number of descriptors
that have been inherited. This is the integer value of the first
inherited descriptor. Subsequent inherited descriptors are numbered
counting up from here. See L{ListenFDs._START}.
@param environ: The environment variable mapping in which to look for the
value to parse.
@return: The integer values of the inherited file descriptors, in order.
"""
try:
count = int(environ["LISTEN_FDS"])
except (KeyError, ValueError):
return []
else:
descriptors = list(range(start, start + count))
# Remove the information from the environment so that a second
# `ListenFDs` cannot find the same information. This is a precaution
# against some application code accidentally trying to handle the same
# inherited descriptor more than once - which probably wouldn't work.
#
# This precaution is perhaps somewhat questionable since it is up to
# the application itself to know whether its handling of the file
# descriptor will actually be safe. Also, nothing stops an
# application from getting the same descriptor more than once using
# multiple calls to `ListenFDs.inheritedDescriptors()` on the same
# `ListenFDs` instance.
del environ["LISTEN_PID"], environ["LISTEN_FDS"]
return descriptors |
Parse the I{LISTEN_FDNAMES} environment variable supplied by systemd.
@param environ: The environment variable mapping in which to look for the
value to parse.
@return: The names of the inherited descriptors, in order. | def _parseNames(environ: Mapping[str, str]) -> Sequence[str]:
"""
Parse the I{LISTEN_FDNAMES} environment variable supplied by systemd.
@param environ: The environment variable mapping in which to look for the
value to parse.
@return: The names of the inherited descriptors, in order.
"""
names = environ.get("LISTEN_FDNAMES", "")
if len(names) > 0:
return tuple(names.split(":"))
return () |
Expansive string formatting for sequence types.
C{list.__str__} and C{dict.__str__} use C{repr()} to display their
elements. This function also turns these sequence types
into strings, but uses C{str()} on their elements instead.
Sequence elements are also displayed on separate lines, and nested
sequences have nested indentation. | def stringyString(object, indentation=""):
"""
Expansive string formatting for sequence types.
C{list.__str__} and C{dict.__str__} use C{repr()} to display their
elements. This function also turns these sequence types
into strings, but uses C{str()} on their elements instead.
Sequence elements are also displayed on separate lines, and nested
sequences have nested indentation.
"""
braces = ""
sl = []
if type(object) is dict:
braces = "{}"
for key, value in object.items():
value = stringyString(value, indentation + " ")
if isMultiline(value):
if endsInNewline(value):
value = value[: -len("\n")]
sl.append(f"{indentation} {key}:\n{value}")
else:
# Oops. Will have to move that indentation.
sl.append(f"{indentation} {key}: {value[len(indentation) + 3 :]}")
elif type(object) is tuple or type(object) is list:
if type(object) is tuple:
braces = "()"
else:
braces = "[]"
for element in object:
element = stringyString(element, indentation + " ")
sl.append(element.rstrip() + ",")
else:
sl[:] = map(lambda s, i=indentation: i + s, str(object).split("\n"))
if not sl:
sl.append(indentation)
if braces:
sl[0] = indentation + braces[0] + sl[0][len(indentation) + 1 :]
sl[-1] = sl[-1] + braces[-1]
s = "\n".join(sl)
if isMultiline(s) and not endsInNewline(s):
s = s + "\n"
return s |
Returns C{True} if this string has a newline in it. | def isMultiline(s):
"""
Returns C{True} if this string has a newline in it.
"""
return s.find("\n") != -1 |
Returns C{True} if this string ends in a newline. | def endsInNewline(s):
"""
Returns C{True} if this string ends in a newline.
"""
return s[-len("\n") :] == "\n" |
Given a string and a column width, return a list of lines.
Caveat: I'm use a stupid greedy word-wrapping
algorythm. I won't put two spaces at the end
of a sentence. I don't do full justification.
And no, I've never even *heard* of hypenation. | def greedyWrap(inString, width=80):
"""
Given a string and a column width, return a list of lines.
Caveat: I'm use a stupid greedy word-wrapping
algorythm. I won't put two spaces at the end
of a sentence. I don't do full justification.
And no, I've never even *heard* of hypenation.
"""
outLines = []
# eww, evil hacks to allow paragraphs delimited by two \ns :(
if inString.find("\n\n") >= 0:
paragraphs = inString.split("\n\n")
for para in paragraphs:
outLines.extend(greedyWrap(para, width) + [""])
return outLines
inWords = inString.split()
column = 0
ptr_line = 0
while inWords:
column = column + len(inWords[ptr_line])
ptr_line = ptr_line + 1
if column > width:
if ptr_line == 1:
# This single word is too long, it will be the whole line.
pass
else:
# We've gone too far, stop the line one word back.
ptr_line = ptr_line - 1
(l, inWords) = (inWords[0:ptr_line], inWords[ptr_line:])
outLines.append(" ".join(l))
ptr_line = 0
column = 0
elif not (len(inWords) > ptr_line):
# Clean up the last bit.
outLines.append(" ".join(inWords))
del inWords[:]
else:
# Space
column = column + 1
# next word
return outLines |
Like a string split, but don't break substrings inside quotes.
>>> splitQuoted('the "hairy monkey" likes pie')
['the', 'hairy monkey', 'likes', 'pie']
Another one of those "someone must have a better solution for
this" things. This implementation is a VERY DUMB hack done too
quickly. | def splitQuoted(s):
"""
Like a string split, but don't break substrings inside quotes.
>>> splitQuoted('the "hairy monkey" likes pie')
['the', 'hairy monkey', 'likes', 'pie']
Another one of those "someone must have a better solution for
this" things. This implementation is a VERY DUMB hack done too
quickly.
"""
out = []
quot = None
phrase = None
for word in s.split():
if phrase is None:
if word and (word[0] in ('"', "'")):
quot = word[0]
word = word[1:]
phrase = []
if phrase is None:
out.append(word)
else:
if word and (word[-1] == quot):
word = word[:-1]
phrase.append(word)
out.append(" ".join(phrase))
phrase = None
else:
phrase.append(word)
return out |
Find whether string C{p} occurs in a read()able object C{f}.
@rtype: C{bool} | def strFile(p, f, caseSensitive=True):
"""
Find whether string C{p} occurs in a read()able object C{f}.
@rtype: C{bool}
"""
buf = type(p)()
buf_len = max(len(p), 2**2**2**2)
if not caseSensitive:
p = p.lower()
while 1:
r = f.read(buf_len - len(p))
if not caseSensitive:
r = r.lower()
bytes_read = len(r)
if bytes_read == 0:
return False
l = len(buf) + bytes_read - buf_len
if l <= 0:
buf = buf + r
else:
buf = buf[l:] + r
if buf.find(p) != -1:
return True |
Make all methods listed in each class' synchronized attribute synchronized.
The synchronized attribute should be a list of strings, consisting of the
names of methods that must be synchronized. If we are running in threaded
mode these methods will be wrapped with a lock. | def synchronize(*klasses):
"""
Make all methods listed in each class' synchronized attribute synchronized.
The synchronized attribute should be a list of strings, consisting of the
names of methods that must be synchronized. If we are running in threaded
mode these methods will be wrapped with a lock.
"""
if threadingmodule is not None:
for klass in klasses:
for methodName in klass.synchronized:
sync = _sync(klass, klass.__dict__[methodName])
setattr(klass, methodName, sync) |
Initialize threading.
Don't bother calling this. If it needs to happen, it will happen. | def init(with_threads=1):
"""Initialize threading.
Don't bother calling this. If it needs to happen, it will happen.
"""
global threaded, _synchLockCreator, XLock
if with_threads:
if not threaded:
if threadingmodule is not None:
threaded = True
class XLock(threadingmodule._RLock):
def __reduce__(self):
return (unpickle_lock, ())
_synchLockCreator = XLock()
else:
raise RuntimeError(
"Cannot initialize threading, platform lacks thread support"
)
else:
if threaded:
raise RuntimeError("Cannot uninitialize threads")
else:
pass |
Are we in the thread responsible for I/O requests (the event loop)? | def isInIOThread():
"""Are we in the thread responsible for I/O requests (the event loop)?"""
return ioThread == getThreadID() |
Mark the current thread as responsible for I/O requests. | def registerAsIOThread():
"""Mark the current thread as responsible for I/O requests."""
global ioThread
ioThread = getThreadID() |
Attriute declaration to preserve mutability on L{URLPath}.
@param name: a public attribute name
@type name: native L{str}
@return: a descriptor which retrieves the private version of the attribute
on get and calls rerealize on set. | def _rereconstituter(name):
"""
Attriute declaration to preserve mutability on L{URLPath}.
@param name: a public attribute name
@type name: native L{str}
@return: a descriptor which retrieves the private version of the attribute
on get and calls rerealize on set.
"""
privateName = "_" + name
return property(
lambda self: getattr(self, privateName),
lambda self, value: (
setattr(
self,
privateName,
value if isinstance(value, bytes) else value.encode("charmap"),
)
or self._reconstitute()
),
) |
Makes doc chunks for option declarations.
Takes a list of dictionaries, each of which may have one or more
of the keys 'long', 'short', 'doc', 'default', 'optType'.
Returns a list of strings.
The strings may be multiple lines,
all of them end with a newline. | def docMakeChunks(optList, width=80):
"""
Makes doc chunks for option declarations.
Takes a list of dictionaries, each of which may have one or more
of the keys 'long', 'short', 'doc', 'default', 'optType'.
Returns a list of strings.
The strings may be multiple lines,
all of them end with a newline.
"""
# XXX: sanity check to make sure we have a sane combination of keys.
# Sort the options so they always appear in the same order
optList.sort(key=lambda o: o.get("short", None) or o.get("long", None))
maxOptLen = 0
for opt in optList:
optLen = len(opt.get("long", ""))
if optLen:
if opt.get("optType", None) == "parameter":
# these take up an extra character
optLen = optLen + 1
maxOptLen = max(optLen, maxOptLen)
colWidth1 = maxOptLen + len(" -s, -- ")
colWidth2 = width - colWidth1
# XXX - impose some sane minimum limit.
# Then if we don't have enough room for the option and the doc
# to share one line, they can take turns on alternating lines.
colFiller1 = " " * colWidth1
optChunks = []
seen = {}
for opt in optList:
if opt.get("short", None) in seen or opt.get("long", None) in seen:
continue
for x in opt.get("short", None), opt.get("long", None):
if x is not None:
seen[x] = 1
optLines = []
comma = " "
if opt.get("short", None):
short = "-%c" % (opt["short"],)
else:
short = ""
if opt.get("long", None):
long = opt["long"]
if opt.get("optType", None) == "parameter":
long = long + "="
long = "%-*s" % (maxOptLen, long)
if short:
comma = ","
else:
long = " " * (maxOptLen + len("--"))
if opt.get("optType", None) == "command":
column1 = " %s " % long
else:
column1 = " %2s%c --%s " % (short, comma, long)
if opt.get("doc", ""):
doc = opt["doc"].strip()
else:
doc = ""
if (opt.get("optType", None) == "parameter") and not (
opt.get("default", None) is None
):
doc = "{} [default: {}]".format(doc, opt["default"])
if (opt.get("optType", None) == "parameter") and opt.get(
"dispatch", None
) is not None:
d = opt["dispatch"]
if isinstance(d, CoerceParameter) and d.doc:
doc = f"{doc}. {d.doc}"
if doc:
column2_l = textwrap.wrap(doc, colWidth2)
else:
column2_l = [""]
optLines.append(f"{column1}{column2_l.pop(0)}\n")
for line in column2_l:
optLines.append(f"{colFiller1}{line}\n")
optChunks.append("".join(optLines))
return optChunks |
Determine whether a function is an optional handler for a I{flag} or an
I{option}.
A I{flag} handler takes no additional arguments. It is used to handle
command-line arguments like I{--nodaemon}.
An I{option} handler takes one argument. It is used to handle command-line
arguments like I{--path=/foo/bar}.
@param method: The bound method object to inspect.
@param name: The name of the option for which the function is a handle.
@type name: L{str}
@raise UsageError: If the method takes more than one argument.
@return: If the method is a flag handler, return C{True}. Otherwise return
C{False}. | def flagFunction(method, name=None):
"""
Determine whether a function is an optional handler for a I{flag} or an
I{option}.
A I{flag} handler takes no additional arguments. It is used to handle
command-line arguments like I{--nodaemon}.
An I{option} handler takes one argument. It is used to handle command-line
arguments like I{--path=/foo/bar}.
@param method: The bound method object to inspect.
@param name: The name of the option for which the function is a handle.
@type name: L{str}
@raise UsageError: If the method takes more than one argument.
@return: If the method is a flag handler, return C{True}. Otherwise return
C{False}.
"""
reqArgs = len(inspect.signature(method).parameters)
if reqArgs > 1:
raise UsageError("Invalid Option function for %s" % (name or method.__name__))
if reqArgs == 1:
return False
return True |
Coerce a string value to an int port number, and checks the validity. | def portCoerce(value):
"""
Coerce a string value to an int port number, and checks the validity.
"""
value = int(value)
if value < 0 or value > 65535:
raise ValueError(f"Port number not in range: {value}")
return value |
Make the elements of a list unique by inserting them into a dictionary.
This must not change the order of the input lst. | def uniquify(lst):
"""
Make the elements of a list unique by inserting them into a dictionary.
This must not change the order of the input lst.
"""
seen = set()
result = []
for k in lst:
if k not in seen:
result.append(k)
seen.add(k)
return result |
Pads a sequence out to n elements,
filling in with a default value if it is not long enough.
If the input sequence is longer than n, raises ValueError.
Details, details:
This returns a new list; it does not extend the original sequence.
The new list contains the values of the original sequence, not copies. | def padTo(n, seq, default=None):
"""
Pads a sequence out to n elements,
filling in with a default value if it is not long enough.
If the input sequence is longer than n, raises ValueError.
Details, details:
This returns a new list; it does not extend the original sequence.
The new list contains the values of the original sequence, not copies.
"""
if len(seq) > n:
raise ValueError("%d elements is more than %d." % (len(seq), n))
blank = [default] * n
blank[: len(seq)] = list(seq)
return blank |
Return the path to a sibling of a file in the filesystem.
This is useful in conjunction with the special C{__file__} attribute
that Python provides for modules, so modules can load associated
resource files. | def sibpath(
path: os.PathLike[AnyStr] | AnyStr, sibling: os.PathLike[AnyStr] | AnyStr
) -> AnyStr:
"""
Return the path to a sibling of a file in the filesystem.
This is useful in conjunction with the special C{__file__} attribute
that Python provides for modules, so modules can load associated
resource files.
"""
return os.path.join(os.path.dirname(os.path.abspath(path)), sibling) |
Helper to turn IOErrors into KeyboardInterrupts. | def _getpass(prompt):
"""
Helper to turn IOErrors into KeyboardInterrupts.
"""
import getpass
try:
return getpass.getpass(prompt)
except OSError as e:
if e.errno == errno.EINTR:
raise KeyboardInterrupt
raise
except EOFError:
raise KeyboardInterrupt |
Obtain a password by prompting or from stdin.
If stdin is a terminal, prompt for a new password, and confirm (if
C{confirm} is true) by asking again to make sure the user typed the same
thing, as keystrokes will not be echoed.
If stdin is not a terminal, and C{forceTTY} is not true, read in a line
and use it as the password, less the trailing newline, if any. If
C{forceTTY} is true, attempt to open a tty and prompt for the password
using it. Raise a RuntimeError if this is not possible.
@returns: C{str} | def getPassword(
prompt="Password: ",
confirm=0,
forceTTY=0,
confirmPrompt="Confirm password: ",
mismatchMessage="Passwords don't match.",
):
"""
Obtain a password by prompting or from stdin.
If stdin is a terminal, prompt for a new password, and confirm (if
C{confirm} is true) by asking again to make sure the user typed the same
thing, as keystrokes will not be echoed.
If stdin is not a terminal, and C{forceTTY} is not true, read in a line
and use it as the password, less the trailing newline, if any. If
C{forceTTY} is true, attempt to open a tty and prompt for the password
using it. Raise a RuntimeError if this is not possible.
@returns: C{str}
"""
isaTTY = hasattr(sys.stdin, "isatty") and sys.stdin.isatty()
old = None
try:
if not isaTTY:
if forceTTY:
try:
old = sys.stdin, sys.stdout
sys.stdin = sys.stdout = open("/dev/tty", "r+")
except BaseException:
raise RuntimeError("Cannot obtain a TTY")
else:
password = sys.stdin.readline()
if password[-1] == "\n":
password = password[:-1]
return password
while 1:
try1 = _getpass(prompt)
if not confirm:
return try1
try2 = _getpass(confirmPrompt)
if try1 == try2:
return try1
else:
sys.stderr.write(mismatchMessage + "\n")
finally:
if old:
sys.stdin.close()
sys.stdin, sys.stdout = old |
Creates a function that will return a string representing a progress bar. | def makeStatBar(width, maxPosition, doneChar="=", undoneChar="-", currentChar=">"):
"""
Creates a function that will return a string representing a progress bar.
"""
aValue = width / float(maxPosition)
def statBar(position, force=0, last=[""]):
assert len(last) == 1, "Don't mess with the last parameter."
done = int(aValue * position)
toDo = width - done - 2
result = f"[{doneChar * done}{currentChar}{undoneChar * toDo}]"
if force:
last[0] = result
return result
if result == last[0]:
return ""
last[0] = result
return result
statBar.__doc__ = """statBar(position, force = 0) -> '[%s%s%s]'-style progress bar
returned string is %d characters long, and the range goes from 0..%d.
The 'position' argument is where the '%s' will be drawn. If force is false,
'' will be returned instead if the resulting progress bar is identical to the
previously returned progress bar.
""" % (
doneChar * 3,
currentChar,
undoneChar * 3,
width,
maxPosition,
currentChar,
)
return statBar |
A trace function for sys.settrace that prints every function or method call. | def spewer(frame, s, ignored):
"""
A trace function for sys.settrace that prints every function or method call.
"""
from twisted.python import reflect
if "self" in frame.f_locals:
se = frame.f_locals["self"]
if hasattr(se, "__class__"):
k = reflect.qual(se.__class__)
else:
k = reflect.qual(type(se))
print(f"method {frame.f_code.co_name} of {k} at {id(se)}")
else:
print(
"function %s in %s, line %s"
% (frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno)
) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.