grail.utils module

Version: 16.2

Table of Contents

Description

A miscellaneous collection of useful general purpose functions and classes.

Classes

class Curry(function, *args, **kws)

Provides a means of 'shimming' for callbacks.

The arguments will be ahead of any other arguments called during the __call__ execution.

Example:

As an example, considering having a list of RTV objects and we want the index into the RTV list to be part of the call back, then you would do something like the following,

def onvarchange(index, var):
   
print "%s is the %d'th item in the list" % (var.name(), index)

   
vars = [rtv.IntegerRTV(name="%d blah" % idx) for idx in range(10)]
   
for var in vars:
      
objsignal.listen(var, const.sigON_CHANGE,
                       
None, utils.Curry(onvarchange, index))

The sigON_CHANGE for vars emits a reference to the variable itself, but to make processing easier in the onvarchange() we've curried in the index of the var within the variable list.

Functions

deprecation(message)
For internal use only. Generates a deprecation warning.
docstringfordisplay(docstr)
Generates readable doc strings for the command prompt.

Note

Prefer to use pydoc.getdoc() from the python standard pydoc module [1] for a cleaner and much more useful implementation of this function.

equivalentlist(seq1, seq2)

Determines if two lists have the same (unordered) contents.

Determines if two lists are equivalent, insofar, as they contain the same number of elements, and in one way or another they contain the same elements. For example, [1, 2, 3] would be equivalent to [3, 1, 2].

extractdict(dict[, with_, sep])

Allows you to pull out a dictionary with_ keys separated with a sep.

Best explained with an example. Say we have a dictionary that looks like,

d = {"button_text":"", "hull_width":"10", "button_bg":"grey"}

And we want to pull out all the 'button' keys, then,

buttond, d = extractdict(d, "button")

Will extract out the button items, and return both the button items and the remaining keywords. Typically you just want to overwrite the old dictionary like I did above. So this leaves us with,

d = {"hull_width":"10"}
buttond = {"text":"", "bg":"grey"}

Notice that the button (with variable) has been dumped in the process.

Arguments:
dict : dictionary
Dictionary to examine and attempt to parse.
with_ : string

The prefix to separate with.

Warning

DEPRECATION NOTICE: Starting with MSGRAIL 4.50, the older with keyword will be deprecated. Instead prefer to use with_. This is to handle a future Python migration, where with becomes a Python keyword. The older with keyword will continue to be supported until the Python version no longer makes it feasible.

sep : string
The separator (so you don't need to use '_' for you dictionary)
Returns:
A tuple containing two dictionaries, one containing the extracted values, and the other containing the remains of the input dictionary. Both dictionaries default to {} no matter what happens.
extractkey(dict, keyword)

Finds and removes a keyword from a dictionary, and returns the value.

Extracts a value from the dictionary, removes that value from the dictionary and returns the value back, if and only if that keyword is in the dictionary. Otherwise, this function will return None for the value.

Returns:
The value for the keyword, or None if now value was found.

Note

The dictionary is not copied, so it will be modified by this operation.

fifth(list_)
Returns the fifth item in a list, or None if no item exists.
findif(pred, list_)

Returns all elements in a list that satisfy the predicate.

The opposite of removeif.

findindex(x, list_)
Returns the first index into the list_ matching x.

Note

This is nearly equivalent calling list_.index(x). The only difference is that the index() method will raise a ValueError [3] if x is not in the list_.

It is recommended that if you have a list that you use the index() attribute. However, this function is still useful for tuples.

finditem(item, list_)

Finds all items within the list.

Scans a list looking for an item and returns all objects in the list that satisfy the equality predicate (==). If no items are found an empty list is returned.

Some examples would be,

>>> utils.finditem("a", ["a", "b", "c"])
['a']
>>> utils.finditem("a", ["a", "b","a", "c", "a"])
['a', 'a', 'a']
>>> utils.finditem("who?", ["bon", "jovi"])
[]
Returns:
A list of found items or an empty list ([]) if no items found.
first(list_)

Returns the first item on a list, or None if list is empty.

This is essentially a safe way to pull the first element out of a list. Consider the case where you list is empty, then a reference to the 0'th index will cause an IndexError, this method just tries and hides those mechanics away for you.

fourth(list_)
Returns the fourth item in a list, or None if no item exists.
gensymname()

Returns a unique symbol name in the form sym# where the # basically ranges from 0 to sys.MAX_INT.

Examples:

>>> gensymname()
symname0
>>> gensymname()
symname1
>>> gensymname()
symname2
is2dlist(list_)
Indicates if a list is a 2D list of the form [ [] [] ...].
isclose(float1, float2[, tol])

Returns true if two floats are approximately equal with respect to the tolerance (default is grail.const.FLOATING_POINT_TOLERANCE).

Warning

DEPRECATED (as of MineSight® Grail v3.4).

Prefer to use the much faster ag.isequal() function or the built-in cmp() function [2].

isdictionary(x)
Returns true if and only if x is a dictionary.
isemptystring(string_)
Predicate indicates if a string (assumes string_ is a string) is empty.
isfunction(func)
Predicate determines if input is a function.
isinteger(num)
Returns true if and only if the number inputted is an integer.
islist(list_)
Indicates if the input is a list or not.
isnatural(num)
Returns true if and only if the number inputed is natural. Natural numbers are the set of all integers greater than 0.
issequence(thing)
Returns true if an object is a list or tuple.
isstring(astring)
Returns true if the value is a string, false otherwise.
istuple(tuple_)
Indicates if the input is a tuple or not.
last(list_)
Returns the last element in a list, or None if no element is found.
makenotimplementedstr(obj, methodnamestr, docstr)

Constructs a consistent "not implemented" string for grail methods.

For internal use only.

Typically used when you require sub-classes to define (override) a superclass method, and you want to make noise if there is a failure to do that. For example,

def overrideme(self):
   
raise NotImplementedError,\
         
utils.makenotimplementedstr(self, "overrideme()",
                                     
self.ovrrideme.__doc__)
numToFormattedString(num, decimal)

Generates a string with a floating point format, especially useful for writing numbers to files.

Takes a number, rounds to the decimal specified and adds trailing 0's to provide a consistent format.

Example:
print numToFormattedString(1.2345, 2) #prints 1.23
print numToFormattedString(1.2)       #prints 1.200
Arguments:
num : float or integer
The number used to produce the formatted string
decimal : integer
The number of decimal places for formatting. Should be > 0. If no decimal is specified, default is 3.
Returns:
String
objectclassname(obj)

Attempts to generate a user friendly name for an object.

Takes an object, and calls repr [2] on it to get a string value; then parses the repr string to return a nice to read string. so instead of

"'<GCheckBox.GCheckBox instance at 0x007668F0>'"

this func will return:

"GCheckBox.GCheckBox"

if the repr() is not an instance or contains the "instance" string, then the repr() string is returned unchanged. The repr() function is a python built-in function [2].

pluralizeif(count, word[, suffix])

Takes a word and applies the suffix if the count is > 1.

Quasi limited to only adding a suffix to a word, so words like fly can't really be pluralized to flies. Likewise, mouse can't convert to mice. But the majority of English words should be able to apply the suffix rule (sometimes the suffix may just be 'es').

Useful for examples such as,

print "Valid %s: %s" + (pluralizeif(len(options), "option"), options)

But pretty darn limited, cause sometimes verbs require re-conjugation and such.

Arguments:
count : integer
Condition to determine if we should pluralize (i.e. greater than 1).
word : string
Word to pluralize (just by adding a suffix).
suffix : string
What you want appended if the count > 1. The default is "s".
readablelist(list_[, conjunction])

Convert a list to a user readable string.

Converts a list structure to something that you can print to a user, for example, the list: ["A", "B", "C", "D"] becomes, "A, B, C, and D".

You can specify and/or via the optional conjunction keyword. The default conjunction is "and".

removeif(pred, list_)

Removes items from the list that satisfy the predicate.

Takes each element in the list and runs it through the predicate, if that predicate succeeds, then that element is removed from the list

removeifequal(item, list_)

Removes an item from the list if '==' is satisfied

Walks through the list and removes all elements that are equal to the inputted item.

rest(list_)

Returns everything but the first element, or [] otherwise.

For example,

>>> import utils
>>> utils.rest([1,2,3])
[2, 3]
>>> utils.rest([1])
[]

Note

Rather than None being returned, we get an empty list ([]).

reverselookup(lookupval, dict)

Searches the dictionary by the values rather than by keys (hence reverse).

Returns: list of keys found that match the lookup value, or an empty list if no keys are found. This raises a UtilsError if the input dictionary is not a dictionary.

rgb2str(rgbtuple)

Converts tuple (RR, GG, BB) to a hex-string representation #RRGGBB.

The tuple should be in decimal notation (i.e. 0-255). This is generally used for converting what is easy to understand numerical values into something that Tkinter wants.

second(list_)
Returns the second item in a list, or None if no item exists.
specialappend(list_, value[, equalto])

Only does a list append if the value is not equalto.

Returns the list.

stringtofloat(string_)

Takes a string and (forgivingly) converts it to a float.

Takes a string_ and attempts to convert the string_ to a float using the python built-in conversion. If the string_ is empty, then we return the value 0.0 as an equivalent representation.

In addition, a side-effect will be that any input value that is in integer form will be converted to float form. Meaning that an input of "1" will return 1.0

This function will generate a UtilsError if we can not convert a string to a floating point representation. For example, if the input value is "Jane".

stringtointeger(string_)

Takes a string and (forgivingly) converts it to an integer.

All strings are converted to an integer (if possible). This means that empty strings are treated as 0, and strings containing floating point numbers are rounded to the nearest integer value.

Otherwise, if the string can not be logically converted to an integer a UtilsError is raised.

Returns:
An integer that closely represents the string value inputted.
sysspawn(cmdlist[, search_path])

Path friendly system spawn function. This spawn command will search the systems PATH environment variable for the executable in the cmdlist. For example to spawn notepad with your own text file, called myfile.txt, you would do something like this,

cmdlist = ["notepad", "myfile.txt"]
utils.sysspawn(cmdlist)
Arguments:
cmdlist : list
Command list in the format: [program_name, arg_1, ..., arg_N].
search_path : integer
Flag (defaults to true) to indicate if the full PATH environment variable listing should be searched for the executable or not.
tf(value)

Warning

DEPRECATED (as of MineSight® Grail v3.4) Use the much more efficient python built-in bool() function [2].

third(list_)
Returns the third item in a list, or None if no item exists
uniquify(alist)

Generates a new list that will only have unique values in it.

Walks through a list and composes a new list only containing unique values for each item in that list. This function guarantees the condition that all elements will remain in place For example, [a, b, c] will return [a, b, c].

Returns:
A list with no duplicate elements
yesnostring(value, yes='Yes', no='No')

Returns a yes or no string based on the value.

Mainly a convenience function for translating something like [] to "No" to make a non-programmer happier.

Returns:
The yes string if the value is non-zero, the no string otherwise.

Data

FALSE TRUE
The values 0 and 1 respectively.

Exception

exception UtilsError
Defines all error signaled by the utility module.

References

[1]"pydoc -- Documentation generator and online help system". Python Library Reference. 30 May 2003. 23 June 2004. <http://www.python.org/doc/2.2.3/lib/module-pydoc.html>
[2](1, 2, 3, 4) "Built-in Functions". Python Library Reference. 30 May 2003. 23 June 2004. <http://www.python.org/doc/2.2.3/lib/built-in-funcs.html>
[3]"Built-in Exceptions" Python Library Reference. 30 May 2003. 23 June 2004. <http://www.python.org/doc/2.2.3/lib/module-exceptions.html>