# ``twisted`.`python`.`reflect``

module documentation
(source)

Standardized versions of various cool and/or strange things that you can do with Python's reflection capabilities.

Class | `InvalidName` | The given name is not a dot-separated list of Python objects.
Class | `ModuleNotFound` | The module associated with the given name doesn't exist and it can't be imported.
Class | `ObjectNotFound` | The object associated with the given name doesn't exist and it can't be imported.
Class | `QueueMethod` | I represent a method that doesn't exist yet.
Function | `accumulateClassDict` | Accumulate all attributes of a given name in a class hierarchy into a single dictionary.
Function | `accumulateClassList` | Accumulate all attributes of a given name in a class hierarchy into a single list.
Function | `accumulateMethods` | Given an object `obj`, add all methods that begin with `prefix`.
Function | `addMethodNamesToDict` | This goes through `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
Function | `filenameToModuleName` | Convert a name in the filesystem to the name of the Python module it is.
Function | `findInstances` | Undocumented
Function | `fullFuncName` | Undocumented
Function | `fullyQualifiedName` | 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.
Function | `getClass` | Return the class or type of object 'obj'.
Function | `isLike` | Undocumented
Function | `isOfType` | Undocumented
Function | `isSame` | Undocumented
Function | `modgrep` | Undocumented
Function | `namedAny` | No summary
Function | `namedModule` | Return a module given its name.
Function | `namedObject` | Get a fully named module-global object.
Function | `objgrep` | `objgrep` finds paths between `start` and `goal`.
Function | `prefixedMethodNames` | Given a class object `classObj`, returns a list of method names that match the string `prefix`.
Function | `prefixedMethods` | Given an object `obj`, returns a list of method objects that match the string `prefix`.
Function | `qual` | Return full import path of a class.
Function | `requireModule` | Try to import a module given its name, returning `default` value if `ImportError` is raised during import.
Function | `safe_repr` | Returns a string representation of an object, or a string containing a traceback, if that object's __repr__ raised an exception.
Function | `safe_str` | Returns a string representation of an object, or a string containing a traceback, if that object's __str__ raised an exception.
Variable | `RegexType` | Undocumented
Class | `_NoModuleFound` | No module was found because none exists.
Function | `_determineClass` | Undocumented
Function | `_determineClassName` | Undocumented
Function | `_importAndCheckStack` | No summary
Function | `_safeFormat` | Helper function for `safe_repr` and `safe_str`.

def accumulateClassDict(classObj, attr, adict, baseClass=None): (source)

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 accumulateClassList(classObj, attr, listObj, baseClass=None): (source)

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 accumulateMethods(obj, dict, prefix='', curClass=None): (source)
Given an object `obj`, add all methods that begin with `prefix`.

Parameters
obj | An arbitrary object to collect methods from.
dict:`dict` | A `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.
prefix:`str` | A native string giving a prefix. Each method of `obj` with a name which begins with this prefix will be returned.
curClass | The class in the inheritance hierarchy at which to start collecting methods. Collection proceeds up. To collect all methods from `obj`, do not pass a value for this parameter.
Returns
`None`

def addMethodNamesToDict(classObj, dict, prefix, baseClass=None): (source)

This goes through `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}.

Parameters
classObj | A class object from which to collect method names.
dict:`dict` | A `dict` which will be updated with the results of the accumulation. Items are added to this dictionary, with method names as keys and `1` as values.
prefix:`str` | A native string giving a prefix. Each method of `classObj` (and base classes of `classObj`) with a name which begins with this prefix will be returned.
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.
Returns
`None`

def filenameToModuleName(fn): (source)

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.

Parameters
fn | A filesystem path to a module or package; `bytes` on Python 2, `bytes` or `unicode` on Python 3.
Returns
`str` | A hopefully importable module name.

def findInstances(start, t): (source)

Undocumented

def fullFuncName(func): (source)

Undocumented

def fullyQualifiedName(obj): (source)
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.

Returns
`str`. | Undocumented

def getClass(obj): (source)
Return the class or type of object 'obj'.
def isLike(a, b): (source)

Undocumented

def isOfType(start, goal): (source)

Undocumented

def isSame(a, b): (source)

Undocumented

def modgrep(goal): (source)

Undocumented

def namedAny(name): (source)
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'.

Parameters
name:`str` | The name of the object to return.
Returns
the Python object identified by 'name'.
Raises
`InvalidName` | If the name is an empty string, starts or ends with a '.', or is otherwise syntactically incorrect.
`ModuleNotFound` | If the name is syntactically correct but the module it specifies cannot be imported because it does not appear to exist.
`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.
`AttributeError` | If an attribute of an object along the way cannot be accessed, or a module along the way is not found.

def namedModule(name): (source)
Return a module given its name.
def namedObject(name): (source)
Get a fully named module-global object.
def objgrep(start, goal, eq=isLike, path='', paths=None, seen=None, showUnknowns=0, maxDepth=None): (source)

`objgrep` finds paths between `start` and `goal`.

Starting at the python object `start`, we will loop over every reachable reference, tring to find the python object `goal` (i.e. every object `candidate` for whom `eq(candidate, goal)` is truthy), and return a `list` of `str`, where each `str` is Python syntax for a path between `start` and `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.

Parameters
start | The object to start looking at.
goal | The object to search for.
eq | A 2-argument predicate which takes an object found by traversing references starting at `start`, as well as `goal`, and returns a boolean.
path | The prefix of the path to include in every return value; empty by default.
paths | The result object to append values to; a list of strings.
seen | A dictionary mapping ints (object IDs) to objects already seen.
showUnknowns | if true, print a message to `stdout` when encountering objects that `objgrep` does not know how to traverse.
maxDepth | The maximum number of object references to attempt traversing before giving up. If an integer, limit to that many links, if `None`, unlimited.
Returns
A list of strings representing python object paths starting at `start` and terminating at `goal`.

def prefixedMethodNames(classObj, prefix): (source)
Given a class object `classObj`, returns a list of method names that match the string `prefix`.

Parameters
classObj | A class object from which to collect method names.
prefix:`str` | A native string giving a prefix. Each method with a name which begins with this prefix will be returned.
Returns
`list` of `str` | A list of the names of matching methods of `classObj` (and base classes of `classObj`).

def prefixedMethods(obj, prefix=''): (source)
Given an object `obj`, returns a list of method objects that match the string `prefix`.

Parameters
obj | An arbitrary object from which to collect methods.
prefix:`str` | A native string giving a prefix. Each method of `obj` with a name which begins with this prefix will be returned.
Returns
`list` | A list of the matching method objects.

def qual(clazz): (source)
Return full import path of a class.
def requireModule(name, default=None): (source)
Try to import a module given its name, returning `default` value if `ImportError` is raised during import.

Parameters
name:`str`. | Module name as it would have been passed to `import`.
default | Value returned in case `ImportError` is raised while importing the module.
Returns
Module or default value.

def safe_repr(o): (source)
Returns a string representation of an object, or a string containing a traceback, if that object's __repr__ raised an exception.

Parameters
o | Any object.
Returns
`str` | Undocumented

def safe_str(o): (source)
Returns a string representation of an object, or a string containing a traceback, if that object's __str__ raised an exception.

Parameters
o:`object` | Any object.
Returns
`str` | Undocumented

RegexType = (source)

Undocumented

def _determineClass(x): (source)

Undocumented

def _determineClassName(x): (source)

Undocumented

def _importAndCheckStack(importName): (source)
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).

Parameters
importName:`str` | The name of the module to import.
Raises
`Exception` | if something bad happens. This can be any type of exception, since nobody knows what loading some arbitrary code might do.
`_NoModuleFound` | if no module was found.

def _safeFormat(formatter, o): (source)

Helper function for `safe_repr` and `safe_str`.

Called when `repr` or `str` fail. Returns a string containing info about `o` and the latest exception.

Parameters
formatter:`type` | `str` or `repr`.
o:`object` | Any object.
Returns
`str` | A string containing information about `o` and the raised exception.