====================== ``grail.utils`` module ====================== .. include:: ..\version.h .. include:: ..\Library_Reference\lib-reference.h .. contents:: Table of Contents :backlinks: top ----------- Description ----------- A miscellaneous collection of useful general purpose functions and classes. ------- Classes ------- class :dc:`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 :c:`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, .. Python:: 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 :d:`sigON_CHANGE` for vars emits a reference to the variable itself, but to make processing easier in the :f:`onvarchange()` we've curried in the index of the var within the variable list. --------- Functions --------- :df:`deprecation(message)` For *internal use only*. Generates a deprecation warning. :df:`docstringfordisplay(docstr)` Generates readable doc strings for the command prompt. .. Note:: Prefer to use :f:`pydoc.getdoc()` from the python standard ``pydoc`` module [#python-lib-pydoc]_ for a cleaner and much more useful implementation of this function. :df:`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]. :df:`extractdict(dict[, with_, sep])` Allows you to pull out a dictionary :a:`with_` keys separated with a :a:`sep`. Best explained with an example. Say we have a dictionary that looks like, .. Python:: d = {"button_text":"", "hull_width":"10", "button_bg":"grey"} And we want to pull out all the 'button' keys, then, .. Python:: 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, .. Python:: d = {"hull_width":"10"} buttond = {"text":"", "bg":"grey"} Notice that the :a:`button` (with variable) has been dumped in the process. Arguments: :a:`dict` : dictionary Dictionary to examine and attempt to parse. :a:`with_` : string The prefix to separate with. .. Warning:: DEPRECATION NOTICE: Starting with MSGRAIL 4.50, the older :a:`with` keyword will be deprecated. Instead prefer to use :a:`with_`. This is to handle a future Python migration, where **with** becomes a Python keyword. The older :a:`with` keyword will continue to be supported until the Python version no longer makes it feasible. :a:`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 :a:`{}` no matter what happens. :df:`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 :d:`None` for the value. Returns: The value for the keyword, or :d:`None` if now value was found. .. Note:: The dictionary is **not copied**, so it will be modified by this operation. :df:`fifth(list\_)` Returns the fifth item in a list, or :d:`None` if no item exists. :df:`findif(pred, list\_)` Returns all elements in a list that satisfy the predicate. The opposite of :f:`removeif`. :df:`findindex(x, list\_)` Returns the first index into the :a:`list\_` matching :a:`x`. .. Note:: This is nearly equivalent calling :f:`list\_.index(x)`. The only difference is that the :f:`index()` method will raise a :e:`ValueError` [#python-lib-builtin-exceptions]_ if x is not in the :a:`list\_`. It is recommended that if you have a list that you use the :f:`index()` attribute. However, this function is still useful for tuples. :df:`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, .. Python:: >>> 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 (:a:`[]`) if no items found. :df:`first(list\_)` Returns the first item on a list, or :d:`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. :df:`fourth(list\_)` Returns the fourth item in a list, or :d:`None` if no item exists. :df:`gensymname()` Returns a unique symbol name in the form sym# where the # basically ranges from 0 to :d:`sys.MAX_INT`. Examples: .. Python:: >>> gensymname() symname0 >>> gensymname() symname1 >>> gensymname() symname2 :df:`is2dlist(list\_)` Indicates if a list is a 2D list of the form [ [] [] ...]. :df:`isclose(float1, float2[, tol])` Returns true if two floats are approximately equal with respect to the tolerance (default is :d:`grail.const.FLOATING_POINT_TOLERANCE`). .. Warning:: DEPRECATED (as of MineSightŪ Grail v3.4). Prefer to use the much faster :f:`ag.isequal()` function or the built-in :f:`cmp()` function [#python-lib-builtin-func]_. :df:`isdictionary(x)` Returns true if and only if :a:`x` is a dictionary. :df:`isemptystring(string\_)` Predicate indicates if a string (assumes :a:`string\_` is a string) is empty. :df:`isfunction(func)` Predicate determines if input is a function. :df:`isinteger(num)` Returns true if and only if the number inputted is an integer. :df:`islist(list\_)` Indicates if the input is a list or not. :df:`isnatural(num)` Returns true if and only if the number inputed is natural. Natural numbers are the set of all integers greater than 0. :df:`issequence(thing)` Returns true if an object is a list or tuple. :df:`isstring(astring)` Returns true if the value is a string, false otherwise. :df:`istuple(tuple_)` Indicates if the input is a tuple or not. :df:`last(list\_)` Returns the last element in a list, or :d:`None` if no element is found. :df:`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, .. Python:: def overrideme(self): raise NotImplementedError,\ utils.makenotimplementedstr(self, "overrideme()", self.ovrrideme.__doc__) :df:`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: .. Python:: print numToFormattedString(1.2345, 2) #prints 1.23 print numToFormattedString(1.2) #prints 1.200 Arguments: :a:`num` : float or integer The number used to produce the formatted string :a:`decimal` : integer The number of decimal places for formatting. Should be > 0. If no decimal is specified, default is 3. Returns: String :df:`objectclassname(obj)` Attempts to generate a user friendly name for an object. Takes an object, and calls :f:`repr` [#python-lib-builtin-func]_ on it to get a string value; then parses the :f:`repr` string to return a nice to read string. so instead of "''" this func will return: "GCheckBox.GCheckBox" if the :f:`repr()` is not an instance or contains the "instance" string, then the :f:`repr()` string is returned unchanged. The :f:`repr()` function is a python built-in function [#python-lib-builtin-func]_. :df:`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, .. Python:: print "Valid %s: %s" + (pluralizeif(len(options), "option"), options) But pretty darn limited, cause sometimes verbs require re-conjugation and such. Arguments: :a:`count` : integer Condition to determine if we should pluralize (i.e. greater than 1). :a:`word` : string Word to pluralize (just by adding a suffix). :a:`suffix` : string What you want appended if the count > 1. The default is "s". :df:`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 :a:`conjunction` keyword. The default conjunction is "and". :df:`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 :df:`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. :df:`rest(list\_)` Returns everything but the first element, or [] otherwise. For example, .. Python:: >>> import utils >>> utils.rest([1,2,3]) [2, 3] >>> utils.rest([1]) [] .. Note:: Rather than :d:`None` being returned, we get an empty list (:a:`[]`). :df:`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 :e:`UtilsError` if the input dictionary is *not* a dictionary. :df:`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. :df:`second(list\_)` Returns the second item in a list, or :d:`None` if no item exists. :df:`specialappend(list\_, value[, equalto])` Only does a list append if the value is not :a:`equalto`. Returns the list. :df:`stringtofloat(string\_)` Takes a string and (forgivingly) converts it to a float. Takes a :a:`string\_` and attempts to convert the :a:`string\_` to a float using the python built-in conversion. If the :a:`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 :e:`UtilsError` if we can not convert a string to a floating point representation. For example, if the input value is "Jane". :df:`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 :e:`UtilsError` is raised. Returns: An integer that closely represents the string value inputted. :df:`sysspawn(cmdlist[, search_path])` Path friendly system spawn function. This spawn command will search the systems PATH environment variable for the executable in the :a:`cmdlist`. For example to spawn notepad with your own text file, called :file:`myfile.txt`, you would do something like this, .. Python:: cmdlist = ["notepad", "myfile.txt"] utils.sysspawn(cmdlist) Arguments: :a:`cmdlist` : list Command list in the format: [:a:`program_name`, :a:`arg_1`, ..., :a:`arg_N`]. :a:`search_path` : integer Flag (defaults to true) to indicate if the full PATH environment variable listing should be searched for the executable or not. :df:`tf(value)` .. Warning:: DEPRECATED (as of MineSightŪ Grail v3.4) Use the much more efficient python built-in :f:`bool()` function [#python-lib-builtin-func]_. :df:`third(list\_)` Returns the third item in a list, or :d:`None` if no item exists :df:`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 :df:`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 ---- :dd:`FALSE` :dd:`TRUE` The values 0 and 1 respectively. --------- Exception --------- exception :de:`UtilsError` Defines all error signaled by the utility module. References ---------- .. [#python-lib-pydoc] "pydoc -- Documentation generator and online help system". *Python Library Reference*. 30 May 2003. 23 June 2004. .. [#python-lib-builtin-func] "Built-in Functions". *Python Library Reference*. 30 May 2003. 23 June 2004. .. [#python-lib-builtin-exceptions] "Built-in Exceptions" *Python Library Reference*. 30 May 2003. 23 June 2004.