Go to the latest version of this document.

# ``twisted`.`python`.`compat``

module documentation
(source)

Compatibility module to provide backwards compatibility for useful Python features.

This is mainly for use of internal Twisted code. We encourage you to use the latest version of Python directly from your code, if possible.

Function | `bytesEnviron` | Return a `dict` of `os.environ` where all text-strings are encoded into `bytes`.
Function | `cmp` | Compare two objects.
Function | `comparable` | Class decorator that ensures support for the special `__cmp__` method.
Function | `currentframe` | In Python 3, `inspect.currentframe` does not take a stack-level argument. Restore that functionality from Python 2 so we don't have to re-implement the `f_back`-walking loop in places where it's called.
Function | `execfile` | Execute a Python script in the given namespaces.
Function | `intToBytes` | Convert the given integer into `bytes`, as ASCII-encoded Arab numeral.
Function | `ioType` | Determine the type which will be returned from the given file object's read() and accepted by its write() method as an argument.
Function | `items` | Return a list of the items of `d`.
Function | `iterbytes` | Return an iterable wrapper for a `bytes` object that provides the behavior of iterating over `bytes` on Python 2.
Function | `iteritems` | Return an iterable of the items of `d`.
Function | `itervalues` | Return an iterable of the values of `d`.
Function | `lazyByteSlice` | Return a memory view of the given bytes-like object.
Function | `nativeString` | Convert `bytes` or `str` to `str` type, using ASCII encoding if conversion is necessary.
Function | `networkString` | Convert a string to `bytes` using ASCII encoding.
Function | `reraise` | Re-raise an exception, with an optional traceback.
Variable | `NativeStringIO` | An in-memory file-like object that operates on the native string type (bytes in Python 2, unicode in Python 3).
Variable | `unicode` | The type of Unicode strings, `unicode` on Python 2 and `str` on Python 3.
Variable | `urllib_parse` | a URL-parsing module (urlparse on Python 2, urllib.parse on Python 3)
Function | `_constructMethod` | Construct a bound method.
Function | `_matchingString` | Some functions, such as `os.path.join`, operate on string arguments which may be bytes or text, and wish to return a value of the same type. In those cases you may wish to have a string constant (in the case of ...
Function | `_pypy3BlockingHack` | Work around https://foss.heptapod.net/pypy/pypy/-/issues/3051 by replacing `socket.fromfd` with a more conservative version.
Variable | `_PYPY` | Undocumented

def bytesEnviron(): (source)

Deprecated since version 21.2.0: `bytesEnviron` was deprecated in Twisted 21.2.0; please use `os.environb` instead.

Return a `dict` of `os.environ` where all text-strings are encoded into `bytes`.

This function is POSIX only; environment variables are always text strings on Windows.

def cmp(a: `object`, b: `object`) -> `int`: (source)

Compare two objects.

Returns a negative number if `a < b`, zero if they are equal, and a positive number if `a > b`.

def comparable(klass): (source)

Class decorator that ensures support for the special `__cmp__` method.

`__eq__`, `__lt__`, etc. methods are added to the class, relying on `__cmp__` to implement their comparisons.

def currentframe(n: `int` = 0) -> `FrameType`: (source)

In Python 3, `inspect.currentframe` does not take a stack-level argument. Restore that functionality from Python 2 so we don't have to re-implement the `f_back`-walking loop in places where it's called.

Parameters
n:`int` | The number of stack levels above the caller to walk.

Returns
`FrameType` | a frame, n levels up the stack from the caller.

def execfile(filename, globals, locals=None): (source)

Execute a Python script in the given namespaces.

Similar to the execfile builtin, but a namespace is mandatory, partly because that's a sensible thing to require, and because otherwise we'd have to do some frame hacking.

This is a compatibility implementation for Python 3 porting, to avoid the use of the deprecated builtin `execfile` function.

def intToBytes(i: `int`) -> `bytes`: (source)

Deprecated since version 21.2.0: `intToBytes` was deprecated in Twisted 21.2.0; please use `b'%d'` instead.

Convert the given integer into `bytes`, as ASCII-encoded Arab numeral.

Parameters
i:`int` | The `int` to convert to `bytes`.

Returns
`bytes` | Undocumented

def ioType(fileIshObject, default=str): (source)

Determine the type which will be returned from the given file object's read() and accepted by its write() method as an argument.

In other words, determine whether the given file is 'opened in text mode'.

Parameters
fileIshObject:`object` | Any object, but ideally one which resembles a file.
default:`type` | A default value to return when the type of `fileIshObject` cannot be determined.

Returns

`type`

There are 3 possible return values:

1. `str`, if the file is unambiguously opened in text mode.
2. `bytes`, if the file is unambiguously opened in binary mode.
3. The `default` parameter, if the given type is not understood.

def items(d): (source)

Deprecated since version 21.2.0: `items` was deprecated in Twisted 21.2.0; please use `list(d.items())` instead.

Return a list of the items of `d`.

Parameters
d:`dict` | Undocumented

Returns
`list` | Undocumented

def iterbytes(originalBytes): (source)

Return an iterable wrapper for a `bytes` object that provides the behavior of iterating over `bytes` on Python 2.

In particular, the results of iteration are the individual bytes (rather than integers as on Python 3).

Parameters
originalBytes | A `bytes` object that will be wrapped.

def iteritems(d): (source)

Deprecated since version 21.2.0: `iteritems` was deprecated in Twisted 21.2.0; please use `d.items()` instead.

Return an iterable of the items of `d`.

Parameters
d:`dict` | Undocumented

Returns
iterable | Undocumented

def itervalues(d): (source)

Deprecated since version 21.2.0: `itervalues` was deprecated in Twisted 21.2.0; please use `d.values()` instead.

Return an iterable of the values of `d`.

Parameters
d:`dict` | Undocumented

Returns
iterable | Undocumented

def lazyByteSlice(object, offset=0, size=None): (source)

Return a memory view of the given bytes-like object.

If an offset is given, the view starts at that offset. If a size is given, the view will only be of that length.

Parameters
object | `bytes` to be sliced.
offset | `int`, starting index of view.
size | Optional, if an `int` is given limit the length of the view to this size.

def nativeString(s: `AnyStr`) -> `str`: (source)

Convert `bytes` or `str` to `str` type, using ASCII encoding if conversion is necessary.

Raises
`UnicodeError` | The input string is not ASCII encodable/decodable.
`TypeError` | The input is neither `bytes` nor `str`.

def networkString(s: `str`) -> `bytes`: (source)

Convert a string to `bytes` using ASCII encoding.

This is useful for sending text-like bytes that are constructed using string interpolation. For example:

        networkString("Hello %d" % (n,))

Parameters
s:`str` | A string to convert to bytes.

Returns
`bytes` | Undocumented

Raises
`UnicodeError` | The input string is not ASCII encodable.
`TypeError` | The input is not `str`.

def reraise(exception, traceback): (source)

Deprecated since version 21.2.0: `reraise` was deprecated in Twisted 21.2.0; please use `raise exception.with_traceback(traceback)` instead.

Re-raise an exception, with an optional traceback.

Re-raised exceptions will be mutated, with their `__traceback__` attribute being set.

Parameters
exception | The exception instance.
traceback | The traceback to use, or `None` indicating a new traceback.

NativeStringIO = (source)

An in-memory file-like object that operates on the native string type (bytes in Python 2, unicode in Python 3).

unicode = (source)

The type of Unicode strings, `unicode` on Python 2 and `str` on Python 3.

urllib_parse = (source)

a URL-parsing module (urlparse on Python 2, urllib.parse on Python 3)

def _constructMethod(cls, name, self): (source)

Construct a bound method.

Parameters
cls:`type` | The class that the method should be bound to.
name:native `str` | The name of the method.
self:any object | The object that the method is bound to.

Returns
`_MethodType` | a bound method

def _matchingString(constantString, inputString): (source)

Some functions, such as `os.path.join`, operate on string arguments which may be bytes or text, and wish to return a value of the same type. In those cases you may wish to have a string constant (in the case of `os.path.join`, that constant would be `os.path.sep`) involved in the parsing or processing, that must be of a matching type in order to use string operations on it. `_matchingString` will take a constant string (either `bytes` or `str`) and convert it to the same type as the input string. `constantString` should contain only characters from ASCII; to ensure this, it will be encoded or decoded regardless.

Parameters
constantString:`str` or `bytes` | A string literal used in processing.
inputString:`str` or `bytes` | A byte string or text string provided by the user.

Returns
the type of `inputString` | `constantString` converted into the same type as `inputString`

def _pypy3BlockingHack(): (source)

Work around https://foss.heptapod.net/pypy/pypy/-/issues/3051 by replacing `socket.fromfd` with a more conservative version.

_PYPY: `bool` = (source)

Undocumented