mrv.util

Epydoc: mrv.util

All kinds of utility methods and classes that are used in more than one modules

Functions

mrv.util.capitalize(s)
Returns:s with first letter capitalized
mrv.util.copyClsMembers(sourcecls, destcls, overwritePrefix=None, forbiddenMembers=[], copyNamespaceGlobally=None)

Copy the members or sourcecls to destcls while ignoring member names in forbiddenMembers It will only copy mebers of this class, not its base classes

Parameters:
  • sourcecls – class whose members should be copied
  • destcls – class to receive members from sourcecls
  • overwritePrefix – if None, existing members on destcls will not be overwritten, if string, the original method will be stored in a name like prefix+originalname (allowing you to access the original method lateron)
  • copyNamespaceGlobally – if not None, the variable contains the name of the namespace as string whose methods should also be copied into the global namespace, possibly overwriting existing ones. For instance, ‘nsmethod’ will be available as obj.nsmethod and as obj.method if the namespace value was ‘ns. The forbiddenMembers list is applied to the original as well as the global name
Note:

this can be useful if you cannot inherit from a class directly because you would get method resolution order problems

Note:

see also the MetaCopyClsMembers meta class

mrv.util.decodeString(valuestr)
Returns:int,float or str from string valuestr - a string that encodes a numeric value or a string
Raises TypeError:
 if the type could not be determined
mrv.util.decodeStringOrList(valuestrOrList)
Returns:as decodeString, but returns a list of appropriate values if the input argument is a list or tuple type
mrv.util.iterNetworkxGraph(graph, startItem, direction=0, prune=<function <lambda> at 0x2eca7d0>, stop=<function <lambda> at 0x2eca848>, depth=-1, branch_first=True, visit_once=True, ignore_startitem=1)
Returns:

iterator yielding pairs of depth, item

Parameters:
  • direction – specifies search direction, either : 0 = items being successors of startItem 1 = items being predecessors of startItem
  • prune – return True if item d,i in graph g should be pruned from result. d is the depth of item i
  • stop – return True if item d,i in graph g, d is the depth of item i stop the search in that direction. It will not be returned.
  • depth – define at which level the iteration should not go deeper if -1, there is no limit if 0, you would only get startitem. i.e. if 1, you would only get the startitem and the first level of predessessors/successors
  • branch_first – if True, items will be returned branch first, otherwise depth first
  • visit_once – if True, items will only be returned once, although they might be encountered several times
  • ignore_startitem – if True, the startItem will be ignored and automatically pruned from the result
Note:

this is an adjusted version of dge.iterShells

mrv.util.list_submodules(path)
Returns:set(submodule_name, ...) list of submodule names that could be imported using __import__
Parameter:path – module path containing the submodules
mrv.util.list_subpackages(path)
Returns:list of sub-package names
mrv.util.make_path(path)
Returns:A path instance of the correct type
Note:use this constructor if you use the Path.set_separator method at runtime to assure you will always create instances of the actual type, and not only of the type you imported last
mrv.util.packageClasses(importBase, packageFile, predicate=<function <lambda> at 0x2eca6e0>)
Returns:

all classes of modules of the given package file that additionally match given predicate

Parameters:
  • importBase – longest import base path whose submodules contain the classes to import
  • packageFile – the filepath to the package, as given in your __file__ variables
  • predicate – receives the class and returns True if it is a class you are looking for
mrv.util.pythonIndex(index, length)
Compute the actual index based on the given index and array length, thus -1 will result in the last array element’s index
mrv.util.uncapitalize(s, preserveAcronymns=False)
Returns:s with first letter lower case
Parameter:preserveAcronymns – enabled ensures that ‘NTSC’ does not become ‘nTSC’
Note:from pymel

Classes

Epydoc: mrv.util.And

class mrv.util.And(*args)

Bases: object

For use with python’s filter method, simulates logical AND Usage: filter(And(f1,f2,fn), sequence)

functions

Epydoc: mrv.util.Call

class mrv.util.Call(func, *args, **kwargs)

Bases: object

Call object encapsulating any code, thus providing a simple facade for it :note: derive from it if a more complex call is required

args
func
kwargs

Epydoc: mrv.util.CallAdv

class mrv.util.CallAdv(func, *args, **kwargs)

Bases: mrv.util.Call

Advanced call class providing additional options:

merge_args:
if True, default True, incoming arguments will be prepended before the static ones
merge_kwargs:
if True, default True, incoming kwargs will be merged into the static ones
args
func
kwargs
merge_args
merge_kwargs

Epydoc: mrv.util.CallOnDeletion

class mrv.util.CallOnDeletion(callableobj)

Bases: object

Call the given callable object once this object is being deleted Its usefull if you want to assure certain code to run once the parent scope of this object looses focus

callableobj

Epydoc: mrv.util.DAGTree

class mrv.util.DAGTree(data=None, name='', **attr)

Bases: networkx.classes.digraph.DiGraph

Adds utility functions to DirectedTree allowing to handle a directed tree like a dag :note: currently this tree does not support instancing :todo: add instancing support

add_cycle(nlist, **attr)
add_edge(u, v, attr_dict=None, **attr)
add_edges_from(ebunch, attr_dict=None, **attr)
add_node(n, attr_dict=None, **attr)
add_nodes_from(nodes, **attr)
add_path(nlist, **attr)
add_star(nlist, **attr)
add_weighted_edges_from(ebunch, **attr)
adjacency_iter()
adjacency_list()
children(n)
Returns:list of children of given node n
children_iter(n)
Returns:iterator with children of given node n
clear()
copy()
degree(nbunch=None, with_labels=False, weighted=False)
degree_iter(nbunch=None, weighted=False)
edges(nbunch=None, data=False)
edges_iter(nbunch=None, data=False)
get_edge_data(u, v, default=None)
get_root(startnode=None)
Returns:the root node of this dag tree
Parameter:startnode – if None, the first node will be used to get the root from (good for single rooted dags), otherwise this node will be used to get the root from - thus it must exist in the dag tree
has_edge(u, v)
has_node(n)
has_predecessor(u, v)
has_successor(u, v)
in_degree(nbunch=None, with_labels=False, weighted=False)
in_degree_iter(nbunch=None, weighted=False)
in_edges(nbunch=None, data=False)
in_edges_iter(nbunch=None, data=False)
is_directed()
is_multigraph()
nbunch_iter(nbunch=None)
neighbors(n)
neighbors_iter(n)
nodes(data=False)
nodes_iter(data=False)
nodes_with_selfloops()
number_of_edges(u=None, v=None)
number_of_nodes()
number_of_selfloops()
order()
out_degree(nbunch=None, with_labels=False, weighted=False)
out_degree_iter(nbunch=None, weighted=False)
out_edges(nbunch=None, data=False)
out_edges_iter(nbunch=None, data=False)
parent(n)
Returns:parent of node n
Note:currently there is only one parent, as instancing is not supported yet
parent_iter(n)
Returns:iterator returning all parents of node n
predecessors(n)
predecessors_iter(n)
remove_edge(u, v)
remove_edges_from(ebunch)
remove_node(n)
remove_nodes_from(nbunch)
reverse(copy=True)
selfloop_edges(data=False)
size(weighted=False)
subgraph(nbunch, copy=True)
successors(n)
successors_iter(n)
to_directed()
to_hierarchy_file(root, output_path)

Write ourselves in hierarchy file format to the given output_path.

Parameter:root – The root of the written file, nodes above it will not be serialized.
Note:Directories are expected to exist
Raises ValueError:
 If an node’s string representation contains a newline or starts with a tab
Note:works best with strings as nodes, which may not contain newlines
to_undirected()

Epydoc: mrv.util

Epydoc: mrv.util.Event

class mrv.util.Event(**kwargs)

Bases: object

Descriptor allowing to easily setup callbacks for classes derived from EventSender

duplicate()
remove(eventfunc)
remove the given function from this event :note: will not raise if eventfunc does not exist
send(*args, **kwargs)

Send our event using the given args

Note:if an event listener is weak referenced and goes out of scope
Note:will catch all event exceptions trown by the methods called
Returns:False if at least one event call threw an exception, true otherwise

Epydoc: mrv.util.EventSender

class mrv.util.EventSender

Bases: object

Base class for all classes that want to provide a common callback interface to supply event information to clients.

Usage: Derive from this class and define your callbacks like:

>>> event = Event()
>>> # Call it using
>>> self.event.send([*args][,**kwargs]])
>>> # Users register using
>>> yourinstance.event = callable
>>> # and deregister using
>>> yourinstance.event.remove(callable)
Note:if use_weakref is True, we will weakref the eventfunction, and deal properly with instance methods which would go out of scope immediatly otherwise
Note:using weak-references to ensure one does not keep objects alive, see Event.use_weakref
clearAllEvents()

Remove all event receivers for all events registered in this instance.

Note:This usually doesn’t need to be called directly, but might be useful in conjunction with other system that do not release your strongly bound instance
classmethod listEventNames()
Returns:list of event ids that exist on our class
sender()
Returns:instance which sent the event you are currently processing
Raises ValueError:
 if no event is currently in progress

Epydoc: mrv.util.InterfaceMaster

class mrv.util.InterfaceMaster

Bases: mrv.interface.iDuplicatable

Base class making the derived class an interface provider, allowing interfaces to be set, queried and used including build-in use

class InterfaceBase

Bases: object

If your interface class is derived from this base, you get access to access to call to the number of your current caller.

Note:You can register an InterfaceBase with several InterfaceMasters and share the caller count respectively
aboutToRemoveFromCaller()
Called once our interface is about to be removed from the current caller - you will not receive a call from it anymore
callerId()

Return the number of the caller that called your interface method

Note:the return value of this method is undefined if called if the method has been called by someone not being an official caller (like yourself)
givenToCaller()
Called once our interface has been given to a new caller. The caller has not made a call yet, but its id can be queried
numCallers()
Returns:number possible callers
InterfaceMaster.InterfaceDescriptor
Descriptor handing out interfaces from our interface dict They allow access to interfaces directly through the InterfaceMaster without calling extra functions
classmethod InterfaceMaster.addSep(item, sep)
Returns:

item with separator added to it ( just once )

Note:

operates best on strings

Parameters:
  • item – item to add separator to
  • sep – the separator
InterfaceMaster.basename()
Returns:basename of this path, ‘/hello/world’ -> ‘world’
InterfaceMaster.children(predicate=<function <lambda> at 0x7f41dd7c2ed8>)
Returns:list of intermediate children of path, [ child1 , child2 ]
Parameter:predicate – return True to include x in result
Note:the child objects returned are supposed to be valid paths, not just relative paths
InterfaceMaster.childrenDeep(order=1, predicate=<function <lambda> at 0x7f41dd7c5050>)
Returns:

list of all children of path, [ child1 , child2 ]

Parameters:
  • order – order enumeration
  • predicate – returns true if x may be returned
Note:

the child objects returned are supposed to be valid paths, not just relative paths

InterfaceMaster.copyFrom(other, *args, **kwargs)
Copy all interface from other to self, use they duplciate method if possibly
InterfaceMaster.copyTo(instance, *args, **kwargs)

Copy the values of ourselves onto the given instance which must be an instance of our class to be compatible. Only the common classes will be copied to instance

Returns:altered instance
Note:instance will be altered during the process
InterfaceMaster.copyToOther(instance, *args, **kwargs)
As copyTo, but does only require the objects to have a common base. It will match the actually compatible base classes and call copyFrom if possible. As more checking is performed, this method performs worse than copyTo
InterfaceMaster.createInstance(*args, **kwargs)

Create and Initialize an instance of self.__class__( ... ) based on your own data

Returns:new instance of self
Note:using self.__class__ instead of an explicit class allows derived classes that do not have anything to duplicate just to use your implementeation
Note:you must support args and kwargs if one of your iDuplicate bases does
InterfaceMaster.duplicate(*args, **kwargs)

Implements a c-style copy constructor by creating a new instance of self and applying the copyFrom methods from base to all classes implementing the copyfrom method. Thus we will call the method directly on the class

Parameters:
  • args – passed to copyFrom and createInstance method to give additional directions
  • kwargs – see param args
InterfaceMaster.fullChildName(childname)
Add the given name to the string version of our instance :return: string with childname added like name _sep childname
InterfaceMaster.interface(interfaceName)
Returns:an interface registered with interfaceName
Raises ValueError:
 if no such interface exists
InterfaceMaster.isPartOf(other)
Returns:True if self is a part of other, and thus can be found in other
Note:operates on strings only
InterfaceMaster.isRoot()
Returns:True if this path is the root of the DAG
InterfaceMaster.isRootOf(other)
Returns:True other starts with self
Note:operates on strings
Note:we assume other has the same type as self, thus the same separator
InterfaceMaster.iterParents(predicate=<function <lambda> at 0x7f41dd7c5230>)
Returns:generator retrieving all parents up to the root
Parameter:predicate – returns True for all x that you want to be returned
InterfaceMaster.listInterfaces()
Returns:list of names indicating interfaces available at our InterfaceMaster
InterfaceMaster.parent()
Returns:parent of this path, ‘/hello/world’ -> ‘/hello’ or None if this path is the dag’s root
InterfaceMaster.parentDeep()
Returns:all parents of this path, ‘/hello/my/world’ -> [ ‘/hello/my’,’/hello’ ]
InterfaceMaster.root()
Returns:the root of the DAG - it has no further parents
InterfaceMaster.setInterface(interfaceName, interfaceInstance)

Set the given interfaceInstance to be handed out once an interface with interfaceName is requested from the provider base

Parameters:
  • interfaceName – should start with i..., i.e. names would be iInterface The name can be used to refer to the interface later on
  • interfaceInstance – instance to be handed out once an interface with the given name is requested by the InterfaceMaster or None if None, the interface will effectively be deleted
Raises ValueError:
 

if given InterfaceBase has a master already

InterfaceMaster.supports(interface_type)
Returns:True if this instance supports the interface of the given type
Parameter:interface_type – Type of the interface you require this instance to support
Note:Must be used in case you only have a weak reference of your interface instance or proxy which is a case where the ordinary isinstance( obj, iInterface ) will not work

Epydoc: mrv.util.MetaCopyClsMembers

class mrv.util.MetaCopyClsMembers

Bases: type

Meta class copying members from given classes onto the type to be created it will read the following attributes from the class dict: forbiddenMembers, overwritePrefix, __virtual_bases__

The virtual bases are a tuple of base classes whose members you whish to receive For information on these members, check the docs of copyClsMembers

mro
mro() -> list return a type’s method resolution order

Epydoc: mrv.util.Or

class mrv.util.Or(*args)

Bases: object

For use with python’s filter method, simulates logical OR Usage: filter(Or(f1,f2,fn), sequence)

functions

Epydoc: mrv.util.PipeSeparatedFile

class mrv.util.PipeSeparatedFile(fileobj)

Bases: object

Read and write simple pipe separated files.

The number of column must remain the same per line Format:

val11 | val2 | valn ...
beginReading()
Start reading the file
beginWriting(columnSizes)

intiialize the writing process

Parameter:columnSizes – list of ints defining the size in characters for each column you plan to feed
Note:When done writing, you have to close the file object yourself (there is no endWriting method here)
readColumnLine()

Generator reading one line after another, returning the stripped columns

Returns:tuple of stripped column strings
Raises ValueError:
 if the column count changes between the lines
writeTokens(tokens)

Write the list of tokens to the file accordingly

Parameter:tokens – one token per column that you want to write
Raises TypeError:
 If column count changed between successive calls

Epydoc: mrv.util.Singleton

class mrv.util.Singleton

Bases: object

Singleton classes can be derived from this class, you can derive from other classes as long as Singleton comes first (and class doesn’t override __new__)

Epydoc: mrv.util.WeakInstFunction

class mrv.util.WeakInstFunction(instancefunction)

Bases: object

Create a proper weak instance to an instance function by weakly binding the instance, not the bound function object. When called, the weakreferenced instance pointer will be retrieved, if possible, to finally make the call. If it could not be retrieved, the call will do nothing.

Epydoc: mrv.util

class mrv.util.iDuplicatable

Bases: mrv.interface.Interface

Simple interface allowing any class to be properly duplicated

Note:to implement this interface, implement createInstance and copyFrom in your class
classmethod addSep(item, sep)
Returns:

item with separator added to it ( just once )

Note:

operates best on strings

Parameters:
  • item – item to add separator to
  • sep – the separator
basename()
Returns:basename of this path, ‘/hello/world’ -> ‘world’
children(predicate=<function <lambda> at 0x7f41dd7c2ed8>)
Returns:list of intermediate children of path, [ child1 , child2 ]
Parameter:predicate – return True to include x in result
Note:the child objects returned are supposed to be valid paths, not just relative paths
childrenDeep(order=1, predicate=<function <lambda> at 0x7f41dd7c5050>)
Returns:

list of all children of path, [ child1 , child2 ]

Parameters:
  • order – order enumeration
  • predicate – returns true if x may be returned
Note:

the child objects returned are supposed to be valid paths, not just relative paths

copyFrom(other, *args, **kwargs)

Copy the data from other into self as good as possible Only copy the data that is unique to your specific class - the data of other classes will be taken care of by them !

Note:you must support args and kwargs if one of your iDuplicate bases does
copyTo(instance, *args, **kwargs)

Copy the values of ourselves onto the given instance which must be an instance of our class to be compatible. Only the common classes will be copied to instance

Returns:altered instance
Note:instance will be altered during the process
copyToOther(instance, *args, **kwargs)
As copyTo, but does only require the objects to have a common base. It will match the actually compatible base classes and call copyFrom if possible. As more checking is performed, this method performs worse than copyTo
createInstance(*args, **kwargs)

Create and Initialize an instance of self.__class__( ... ) based on your own data

Returns:new instance of self
Note:using self.__class__ instead of an explicit class allows derived classes that do not have anything to duplicate just to use your implementeation
Note:you must support args and kwargs if one of your iDuplicate bases does
duplicate(*args, **kwargs)

Implements a c-style copy constructor by creating a new instance of self and applying the copyFrom methods from base to all classes implementing the copyfrom method. Thus we will call the method directly on the class

Parameters:
  • args – passed to copyFrom and createInstance method to give additional directions
  • kwargs – see param args
fullChildName(childname)
Add the given name to the string version of our instance :return: string with childname added like name _sep childname
isPartOf(other)
Returns:True if self is a part of other, and thus can be found in other
Note:operates on strings only
isRoot()
Returns:True if this path is the root of the DAG
isRootOf(other)
Returns:True other starts with self
Note:operates on strings
Note:we assume other has the same type as self, thus the same separator
iterParents(predicate=<function <lambda> at 0x7f41dd7c5230>)
Returns:generator retrieving all parents up to the root
Parameter:predicate – returns True for all x that you want to be returned
parent()
Returns:parent of this path, ‘/hello/world’ -> ‘/hello’ or None if this path is the dag’s root
parentDeep()
Returns:all parents of this path, ‘/hello/my/world’ -> [ ‘/hello/my’,’/hello’ ]
root()
Returns:the root of the DAG - it has no further parents
supports(interface_type)
Returns:True if this instance supports the interface of the given type
Parameter:interface_type – Type of the interface you require this instance to support
Note:Must be used in case you only have a weak reference of your interface instance or proxy which is a case where the ordinary isinstance( obj, iInterface ) will not work

Table Of Contents

Previous topic

mrv.mdp

Next topic

mrv.mdepparse

This Page